[英]What is wrong with my List<T>.Distinct()?
I have a class MyItems that implements IEqualityComparer and overrides the following methods: 我有一个实现IEqualityComparer的类MyItems并覆盖以下方法:
public bool Equals(MyItems item1, MyItems item2)
{
return (item1.ID == item2.ID && item1.itemName.Equals(item2));
}
public int GetHashCode(MyItems item)
{
return item.ID.GetHashCode() ^ item.itemName.GetHashCode();
}
First, why is GetHashCode
necessary? 首先,为什么
GetHashCode
是必要的? I understand overriding the Equals
method, however, the GetHashCode
necessity has eluded me. 我理解覆盖
Equals
方法,然而, GetHashCode
必要性已经躲过了我。
Second, this doesn't appear to be working. 其次,这似乎不起作用。 Is there something I'm doing wrong here?
我有什么问题吗? Where I don't understand the
GetHashCode,
that maybe where I am tripping up. 我不明白
GetHashCode,
也许我在绊倒的地方。
The Distinct
method works as follows: Distinct
方法的工作原理如下:
GetHashCode
. GetHashCode
检查这两个对象是否具有相同的哈希码。 Equals
. Equals
。 The GetHashCode
is a first check for the more expensive check: Equals
GetHashCode
是对更昂贵的支票的第一次检查: Equals
Your Equals
method has an error: 您的
Equals
方法有错误:
return (item1.ID == item2.ID && item1.itemName.Equals(item2));
Should be: 应该:
return (item1.ID == item2.ID && item1.itemName.Equals(item2.itemName));
// ^^^^^^^^^
Also, if the List or the array type you're using isn't of <MyItems>
type you also need to override the Equals method. 此外,如果您使用的List或数组类型不是
<MyItems>
类型,则还需要覆盖Equals方法。
If you want to compare objects you should override Equals(object obj)
in their class. 如果要比较对象,则应在其类中重写
Equals(object obj)
。
Also, whenever you override Equals(object obj)
it is good practice to override GetHashCode
此外,每当您重写
Equals(object obj)
,最好覆盖GetHashCode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.