Occasionally when using LINQ, I want to use the Distinct() extension, but in order to do so against a non-primitive object, I would need to create a class to implement IEqualityComparer. That usually seems like more trouble than its worth. I usually end up searching and find this stack overflow answer. It’s a great idea, but it only supports a single property, and uses a HashSet to keep distinct values. I like the approach for the most part, but I came up with something new today that I want to share.

Instead of implementing an extension method, I created a reusable equality comparer that works against any object:

This can be used against any object type like so:

List<MyObjectType> objects = somelist;
var distinctObjects = objects.Distinct(new DelegateEqualityComparer((x, y) => x.property == y.property, x => x.GetHashCode());

Leave a Reply

Your email address will not be published. Required fields are marked *