【发布时间】:2017-06-22 23:58:51
【问题描述】:
我想从电话簿中检索比尔的电话号码。
class PersonsName
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
// Dictionary Class, add contacts to phone book
Dictionary<PersonsName, int> phoneBook = new Dictionary<PersonsName, int>()
{
{new PersonsName {FirstName = "Bill", LastName = "Gates" }, 5550100 },
{new PersonsName {FirstName = "Mark", LastName = "Zuckerberg" }, 5551438 }
};
为什么下面给我一个找不到密钥的异常?如何在不遍历字典的情况下检索电话号码?
PersonsName personA = new PersonsName { FirstName = "Bill", LastName = "Gates" };
int billssNumber = phoneBook[personA]; //key not found
【问题讨论】:
-
如果你真的需要它,你将不得不覆盖 Equals 方法。这是一个例子:stackoverflow.com/questions/634826/…
-
您必须覆盖
GetHashCode和Equals并且将您的对象设为只读,以将其用作字典中的键。 -
@Jannik - 请不要删除这样的内容。很难理解评论历史记录。
-
获取元素的方式不对,试试这样。
PersonsName personA = new PersonsName { FirstName = "Bill", LastName = "Gates" }; int billssNumber = phoneBook.First(x=>x.Key.FirstName==personA.FirstName &&x.Key.LastName==personA.LastName).Value; -
@MAdeelKhalid:这将在
Keys集合中执行 O(N) 搜索,而不是通过哈希码进行搜索。因此,使用字典不会有任何好处 - 使用常规集合可以实现相同的性能,例如List<>。
标签: c# dictionary generics