Linq Distinct LambdaComparer

 public class LambdaComparer<T> : IEqualityComparer<T> {
        private readonly Func<T, T, bool> _comparer;
        private readonly Func<T, int> _hash;

        public LambdaComparer(Func<T, T, bool> comparer) :
          this(comparer, o => 0) { }

        public LambdaComparer(Func<T, T, bool> comparer, Func<T, int> hash) {
            if (comparer == null) throw new ArgumentNullException("comparer");
            if (hash == null) throw new ArgumentNullException("hash");
            _comparer = comparer;
            _hash = hash;
        }

        public bool Equals(T x, T y) {
            return _comparer(x, y);
        }

        public int GetHashCode(T obj) {
            return _hash(obj);
        }
    }

使用:

var productComparer = new LambdaComparer<GetReserveFaultyRulesByIdProductOutput>((x1, x2) => x1.ProductId == x2.ProductId);

());

products = products
.Where(x => x.ProductId != null)
.Distinct(productComparer).ToList();

猜你喜欢

转载自www.cnblogs.com/yangzn/p/11434788.html