LINQ Select Distinct with Anonymous Types

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.

Leave a Comment