Using .Select and .Where in a single LINQ statement

In order for Enumerable.Distinct to work for your type, you can implement IEquatable<T> and provide suitable definitions for Equals and GetHashCode, otherwise it will use the default implementation: comparing for reference equality (assuming that you are using a reference type).

From the manual:

The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, Default, to compare values.

The default equality comparer, Default, is used to compare values of the types that implement the IEquatable generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.

In your case it looks like you might just need to compare the IDs, but you may also want to compare other fields too depending on what it means for you that two objects are “the same”.

You can also consider using DistinctBy from morelinq.

Note that this is LINQ to Objects only, but I assume that’s what you are using.

Yet another option is to combine GroupBy and First:

 var query = // your query here...
    .GroupBy(x => x.Id)
    .Select(g => g.First());

This would also work in LINQ to SQL, for example.

Leave a Comment