Monday, August 11, 2014

Getting Distinct from a List

Sometimes you have a list of complex objects that you need to pare down to be a list of distinct complex objects.  LINQ offers a way to do that, but unless you've done it before it's not immediately obvious as to what you need to do.  There are two ways to do it, and they're actually pretty easy to implement.

If the complex object is your own creation, just implement IEquatable where T is the type of the object.  Something like this:



Once you've implemented IEquatable on your class, you just have to invoke the .Distinct() call on your list.  Here you go:



Here are the results of the IEquatable approach:


If you find yourself in a situation where the complex object can't be extended to implement IEquatable, there's a solution for that, too.  You'll create an additional class that implements IEqualityComparer and then specify that when you invoke the .Distinct() call on your list.







Here are the results of using the IEqualityComparer approach:

No comments:

Post a Comment