Why we implement GetHashCode in IEqualityComparer?
I want to get distinct items from List
in C# by using IEqualityComparer
interface. But I don't know about GetH开发者_如何学JAVAashCode
. 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.
You can use the Distinct
extension method passing it your custom equality comparer.
The reason why you need GetHashCode()
is that without it you need O(n^2)
comparisons. With GetHashCode()
the items can be divided into buckets, which leads to O(n)
for a good hash implementation.
If the item type is your own, you can override Equals
and GetHashCode
in the type itself instead of creating an IEqualityComparer<T>
And how can I call Equals method to get distinct items from a list having user define data type.
Use the overload of Enumerable.Distinct
that takes an IEqualityComparer
to get the distinct items from a sequence using your custom equality comparer.
Why we implement GetHashCode in IEqualityComparer?
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).
Why we implement GetHashCode in IEqualityComparer?
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()?
精彩评论