简体   繁体   English

为什么我们在IEqualityComparer中实现GetHashCode?

[英]Why we implement GetHashCode in IEqualityComparer?

I want to get distinct items from List in C# by using IEqualityComparer interface. 我想通过使用IEqualityComparer接口从C#中的List获取不同的项目。 But I don't know about GetHashCode . 但我不知道GetHashCode I have implement both GetHashCode and Equals methods. 我实现了GetHashCodeEquals方法。 And how can I call Equals method to get distinct items from a list having user define data type. 如何调用Equals方法从具有用户定义数据类型的列表中获取不同的项目。

And how can I call Equals method to get distinct items from a list having user define data type. 如何调用Equals方法从具有用户定义数据类型的列表中获取不同的项目。

Use the overload of Enumerable.Distinct that takes an IEqualityComparer to get the distinct items from a sequence using your custom equality comparer. 使用Enumerable.Distinct重载 ,它使用IEqualityComparer使用自定义相等比较器从序列中获取不同的项。

Why we implement GetHashCode in IEqualityComparer? 为什么我们在IEqualityComparer中实现GetHashCode?

So that the IEqualityComparer can be used as a test for equality in a hash table (hash the items as per the IEqualityComparer.GetHashCode method, use IEqualityComparer.Equals to check for equality when needed (searching for an item in the hash table, for example). 因此, IEqualityComparer可以用作哈希表中的相等性测试(根据IEqualityComparer.GetHashCode方法对项进行哈希,使用IEqualityComparer.Equals在需要时检查相等性(例如,在哈希表中搜索项目) )。

You can use the Distinct extension method passing it your custom equality comparer. 您可以使用Distinct扩展方法将自定义相等比较器传递给它。

The reason why you need GetHashCode() is that without it you need O(n^2) comparisons. 你需要GetHashCode()的原因是没有它你需要进行O(n^2)比较。 With GetHashCode() the items can be divided into buckets, which leads to O(n) for a good hash implementation. 使用GetHashCode() ,项目可以分为多个桶,这样就可以通过O(n)实现良好的哈希实现。

If the item type is your own, you can override Equals and GetHashCode in the type itself instead of creating an IEqualityComparer<T> 如果项类型是您自己的,则可以在类型本身中重写EqualsGetHashCode ,而不是创建IEqualityComparer<T>

Why we implement GetHashCode in IEqualityComparer? 为什么我们在IEqualityComparer中实现GetHashCode?

Because it gets called on IEqualityComparer, usually first, before Equals, at least for the LINQ extension methods which require IEqualityComparer. 因为它在IEqualityComparer上调用,通常首先在Equals之前,至少对于需要IEqualityComparer的LINQ扩展方法。 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. 否则,你是否真的需要实现GetHashCode以确定相等性是有问题的,因为你可以使用Equals方法。 Why does LINQ prefer to call GetHashCode? 为什么LINQ更喜欢调用GetHashCode? See Why use GetHashCode() over Equals()? 请参阅为什么使用GetHashCode()而不是Equals()?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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