LINQ Select Distinct with Anonymous Types

GWLlosa picture GWLlosa · Feb 12, 2009 · Viewed 98k times · Source

So I have a collection of objects. The exact type isn't important. From it I want to extract all the unique pairs of a pair of particular properties, thusly:

myObjectCollection.Select(item=>new
                                {
                                     Alpha = item.propOne,
                                     Bravo = item.propTwo
                                }
                 ).Distinct();

So my question is: Will Distinct in this case use the default object equals (which will be useless to me, since each object is new) or can it be told to do a different equals (in this case, equal values of Alpha and Bravo => equal instances)? Is there any way to achieve that result, if this doesn't do it?

Answer

Matt Hamilton picture Matt Hamilton · Feb 12, 2009

Have a read through K. Scott Allen's excellent post here:

And Equality for All ... Anonymous Types

The short answer (and I quote):

Turns out the C# compiler overrides Equals and GetHashCode for anonymous types. The implementation of the two overridden methods uses all the public properties on the type to compute an object's hash code and test for equality. If two objects of the same anonymous type have all the same values for their properties – the objects are equal.

So it's totally safe to use the Distinct() method on a query that returns anonymous types.