Right, so I have an enumerable and wish to get distinct values from it.
Using System.Linq
, there\'s of course an extension method called Distinct<
No there is no such extension method overload for this. I've found this frustrating myself in the past and as such I usually write a helper class to deal with this problem. The goal is to convert a Func
to IEqualityComparer
.
Example
public class EqualityFactory {
private sealed class Impl : IEqualityComparer {
private Func m_del;
private IEqualityComparer m_comp;
public Impl(Func del) {
m_del = del;
m_comp = EqualityComparer.Default;
}
public bool Equals(T left, T right) {
return m_del(left, right);
}
public int GetHashCode(T value) {
return m_comp.GetHashCode(value);
}
}
public static IEqualityComparer Create(Func del) {
return new Impl(del);
}
}
This allows you to write the following
var distinctValues = myCustomerList
.Distinct(EqualityFactory.Create((c1, c2) => c1.CustomerId == c2.CustomerId));