LINQ's Distinct() on a particular property

后端 未结 20 2126
一向
一向 2020-11-21 05:05

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

20条回答
  •  春和景丽
    2020-11-21 06:01

    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...)

提交回复
热议问题