LINQ: Distinct values

前端 未结 7 1133
一生所求
一生所求 2020-11-22 16:29

I have the following item set from an XML:

id           category

5            1
5            3
5            4
5            3
5            3
<
相关标签:
7条回答
  • 2020-11-22 17:12

    For any one still looking; here's another way of implementing a custom lambda comparer.

    public class LambdaComparer<T> : IEqualityComparer<T>
        {
            private readonly Func<T, T, bool> _expression;
    
            public LambdaComparer(Func<T, T, bool> lambda)
            {
                _expression = lambda;
            }
    
            public bool Equals(T x, T y)
            {
                return _expression(x, y);
            }
    
            public int GetHashCode(T obj)
            {
                /*
                 If you just return 0 for the hash the Equals comparer will kick in. 
                 The underlying evaluation checks the hash and then short circuits the evaluation if it is false.
                 Otherwise, it checks the Equals. If you force the hash to be true (by assuming 0 for both objects), 
                 you will always fall through to the Equals check which is what we are always going for.
                */
                return 0;
            }
        }
    

    you can then create an extension for the linq Distinct that can take in lambda's

       public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list,  Func<T, T, bool> lambda)
            {
                return list.Distinct(new LambdaComparer<T>(lambda));
            }  
    

    Usage:

    var availableItems = list.Distinct((p, p1) => p.Id== p1.Id);
    
    0 讨论(0)
提交回复
热议问题