Search code examples
c#equalsgethashcodeiequalitycomparer

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 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.


Solution

  • 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).