I want to get the distinct values in a list, but not by the standard equality comparison.
What I want to do is something like this:
return myList.Dis
It's annoying, certainly. It's also part of my "MoreLINQ" project which I must pay some attention to at some point :) There are plenty of other operations which make sense when acting on a projection, but returning the original - MaxBy and MinBy spring to mind.
As you say, it's easy to write - although I prefer the name "DistinctBy" to match OrderBy etc. Here's my implementation if you're interested:
public static IEnumerable DistinctBy
(this IEnumerable source,
Func keySelector)
{
return source.DistinctBy(keySelector,
EqualityComparer.Default);
}
public static IEnumerable DistinctBy
(this IEnumerable source,
Func keySelector,
IEqualityComparer comparer)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (keySelector == null)
{
throw new ArgumentNullException("keySelector");
}
if (comparer == null)
{
throw new ArgumentNullException("comparer");
}
return DistinctByImpl(source, keySelector, comparer);
}
private static IEnumerable DistinctByImpl
(IEnumerable source,
Func keySelector,
IEqualityComparer comparer)
{
HashSet knownKeys = new HashSet(comparer);
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}