I am playing with LINQ to learn about it, but I can\'t figure out how to use Distinct
when I do not have a simple list (a simple list of integers is pretty easy
Personally I use the following class:
public class LambdaEqualityComparer :
IEqualityComparer
{
private Func _selector;
public LambdaEqualityComparer(Func selector)
{
_selector = selector;
}
public bool Equals(TSource obj, TSource other)
{
return _selector(obj).Equals(_selector(other));
}
public int GetHashCode(TSource obj)
{
return _selector(obj).GetHashCode();
}
}
Then, an extension method:
public static IEnumerable Distinct(
this IEnumerable source, Func selector)
{
return source.Distinct(new LambdaEqualityComparer(selector));
}
Finally, the intended usage:
var dates = new List() { /* ... */ }
var distinctYears = dates.Distinct(date => date.Year);
The advantage I found using this approach is the re-usage of LambdaEqualityComparer
class for other methods that accept an IEqualityComparer
. (Oh, and I leave the yield
stuff to the original LINQ implementation...)