Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
NASSER Avatar asked Jan 19 '23 14:01

NASSER


1 Answers

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>

like image 129
CodesInChaos Avatar answered Jan 26 '23 00:01

CodesInChaos