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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With