简体   繁体   English

我的清单出了什么问题 <T> 。不同()?

[英]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,也许我在绊倒的地方。

To answer your first question, just look here for more information. 要回答您的第一个问题,请查看此处以获取更多信息。

To answer your second question: You forgot item2 should be item2.itemName 回答你的第二个问题:你忘记了item2应该是item2.itemName

return (item1.ID == item2.ID && item1.itemName.Equals(item2.itemName));

The Distinct method works as follows: Distinct方法的工作原理如下:

  1. Check if the two objects has the same hash code using GetHashCode . 使用GetHashCode检查这两个对象是否具有相同的哈希码。
  2. If they do, now make sure they absolutely equals with 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM