LINQ provides a Distinct() method, but in order to find distinct elements in a list of some target class, we must first implement the IEqualityComparer<T> interface in our target class. That’s what Distinct() uses in order to compute whether one element is the same as another element. Implementing IEqualityComparer<T>, however, is not so straightforward as it requires us to override Equals() and GetHashCode() methods. Most of the times if all we need to do is just to find non-duplicated elements in a given list, IEqualityComparer<T> route seems like an overkill.

Other developers have come up with some slick ways to solve this problem like creating a generic EqualityComparer<T> and using HashSet<T>, but I find both of those methods to be more complex solutions to a simpler problem.

I usually use a much simpler way to accomplish the same task which I will share with you below. Consider the following rather simple Customer class:

We initialize this class with some customers as follows:

So far so good! Now all we need is a list of distinct elements by, let’s say, FirstName (find all elements that have different first names). We can do that by first grouping our list by FirstName, and then selecting only the first element out of each group as follows:

Easy enough? Now let’s say we need to find out whether or not the list actually contains any duplicates to begin with. We can also do that easily by again grouping and then computing whether or not any of the groups contain more than 1 elements as follows:

I hope that this simplifies your code.

Post a Comment

2 Comments on "Finding Distinct Elements In A List(T)"

Sort by:   newest | oldest | most voted

Interesting.

For many years I used to loop through the list. This is great!

wpDiscuz