Distinct() with lambda?

前端 未结 18 969
南旧
南旧 2020-11-22 06:04

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<

18条回答
  •  情歌与酒
    2020-11-22 06:46

    You can use LambdaEqualityComparer:

    var distinctValues
        = myCustomerList.Distinct(new LambdaEqualityComparer((c1, c2) => c1.CustomerId == c2.CustomerId));
    
    
    public class LambdaEqualityComparer : IEqualityComparer
        {
            public LambdaEqualityComparer(Func equalsFunction)
            {
                _equalsFunction = equalsFunction;
            }
    
            public bool Equals(T x, T y)
            {
                return _equalsFunction(x, y);
            }
    
            public int GetHashCode(T obj)
            {
                return obj.GetHashCode();
            }
    
            private readonly Func _equalsFunction;
        }
    

提交回复
热议问题