Short question:
Is there a simple way in LINQ to objects to get a distinct list of objects from a list based on a key property on the objects.
What about a throw away IEqualityComparer
generic class?
public class ThrowAwayEqualityComparer : IEqualityComparer
{
Func comparer;
public ThrowAwayEqualityComparer(Func comparer)
{
this.comparer = comparer;
}
public bool Equals(T a, T b)
{
return comparer(a, b);
}
public int GetHashCode(T a)
{
return a.GetHashCode();
}
}
So now you can use Distinct
with a custom comparer.
var distinctImages = allImages.Distinct(
new ThrowAwayEqualityComparer((a, b) => a.Key == b.Key));
You might be able to get away with the
, but I'm not sure if the compiler could infer the type (don't have access to it right now.)
And in an additional extension method:
public static class IEnumerableExtensions
{
public static IEnumerable Distinct(this IEnumerable @this, Func comparer)
{
return @this.Distinct(new ThrowAwayEqualityComparer(comparer);
}
private class ThrowAwayEqualityComparer...
}