为什么我们在 IEqualityComparer 中实现 GetHashCode?
我想通过使用 IEqualityComparer
接口从 C# 中的 List
获取不同的项目。但我不知道 GetHashCode
。我已经实现了 GetHashCode 和 Equals 方法。如何调用 Equals
方法从具有用户定义数据类型的列表中获取不同的项目。
I want to get distinct items from List
in C# by using IEqualityComparer
interface. But I don't know about GetHashCode
. I have implement both GetHashCode
and Equals
methods. And how can I call Equals
method to get distinct items from a list having user define data type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Distinct
扩展方法将您的自定义相等比较器传递给它。您需要
GetHashCode()
的原因是,如果没有它,您就需要O(n^2)
比较。使用GetHashCode()
可以将项目划分为存储桶,这导致良好的哈希实现需要O(n)
。如果项目类型是您自己的,您可以重写类型本身中的
Equals
和GetHashCode
,而不是创建IEqualityComparer
You can use the
Distinct
extension method passing it your custom equality comparer.The reason why you need
GetHashCode()
is that without it you needO(n^2)
comparisons. WithGetHashCode()
the items can be divided into buckets, which leads toO(n)
for a good hash implementation.If the item type is your own, you can override
Equals
andGetHashCode
in the type itself instead of creating anIEqualityComparer<T>
使用重载
Enumerable.Distinct
使用IEqualityComparer
使用自定义相等比较器从序列中获取不同的项目。因此,
IEqualityComparer
可以用作哈希表中的相等性测试(根据IEqualityComparer.GetHashCode
方法对项目进行哈希处理,请使用IEqualityComparer.Equals< /code> 在需要时检查相等性(例如,在哈希表中搜索项目)。
Use the overload of
Enumerable.Distinct
that takes anIEqualityComparer
to get the distinct items from a sequence using your custom equality comparer.So that the
IEqualityComparer
can be used as a test for equality in a hash table (hash the items as per theIEqualityComparer.GetHashCode
method, useIEqualityComparer.Equals
to check for equality when needed (searching for an item in the hash table, for example).因为它在 IEqualityComparer 上被调用,通常首先在 Equals 之前调用,至少对于需要 IEqualityComparer 的 LINQ 扩展方法来说是这样。否则,您是否真的需要实现 GetHashCode 来确定相等性将是值得怀疑的,因为您只需使用 Equals 方法即可。为什么LINQ更喜欢调用GetHashCode?看
为什么使用 GetHashCode() 而不是 Equals()?
Because it gets called on IEqualityComparer, usually first, before Equals, at least for the LINQ extension methods which require IEqualityComparer. Otherwise it would be questionable whether you'd really need to implement GetHashCode for determining equality, since you could just use the Equals method for that. Why does LINQ prefer to call GetHashCode? See
Why use GetHashCode() over Equals()?