LINQ’s Distinct extension has largely been a disappointment to me. Sure, it’s nice when I’m working with a collection of integers, but more often than not, I’m working with a collection of objects and don’t have an IEqualityComparer<TSource> available to me. I know I could just create one, but I just want to use a lambda like just about everything else I do with LINQ!
To the internet!, right? I learned I could use the following trick to accomplish what I want:
collection .GroupBy(x => x.key) .Select(x => x.First());
Works like a charm, but I got tired of dot-GroupBy-dot-Select-ing and adding a comment about what I was doing for future maintainers, and I think it’s a lot better to just chuck it into an extension method.
public static IEnumerable<TSource> DistinctBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector { return source ?.GroupBy(keySelector) .Select(grp => grp.First()); }
Ahh, nice! Alternatively, could score this functionality by adding MoreLINQ to your project. On a neat side-note, you can also cherry-pick which MoreLINQ functionality you want by installing individual packages.
I actually found that Distinct is really useful with Entity Framework, since it literally translates to a SQL distinct statement. I definitely ran into the same problems that you did with projects that weren’t using EF though.