How to implement IEqualityComparer to return distinct values?
An EqualityComparer
is not the way to go - it can only filter your result set in memory eg:
var objects = yourResults.ToEnumerable().Distinct(yourEqualityComparer);
You can use the GroupBy
method to group by IDs and the First
method to let your database only retrieve a unique entry per ID eg:
var objects = yourResults.GroupBy(o => o.Id).Select(g => g.First());
rich.okelly and Ladislav Mrnka are both correct in different ways.
Both their answers deal with the fact that the IEqualityComparer<T>
's methods won't be translated to SQL.
I think it's worth looking at the pros and cons of each, which will take a bit more than a comment.
rich's approach re-writes the query to a different query with the same ultimate result. Their code should result in more or less how you would efficiently do this with hand-coded SQL.
Ladislav's pulls it out of the database at the point before the distinct, and then an in-memory approach will work.
Since the database is great at doing the sort of grouping and filtering rich's depends upon, it will likely be the most performant in this case. You could though find that the complexity of what's going on prior to this grouping is such that Linq-to-entities doesn't nicely generate a single query but rather produces a bunch of queries and then does some of the work in-memory, which could be pretty nasty.
Generally grouping is more expensive than distinct on in-memory cases (especially if you bring it into memory with AsList()
rather than AsEnumerable()
). So if either you were already going to bring it into memory at this stage due to some other requirement, it would be more performant.
It would also be the only choice if your equality definition was something that didn't relate well to what is available just in the database, and of course it allows you to switch equality definitions if you wanted to do so based on an IEqualityComparer<T>
passed as a parameter.
In all, rich's is the answer I'd say would be most-likely to be the best choice here, but the different pros and cons to Ladislav's compared to rich's makes it also well worth studying and considering.