Generic IEqualityComparer and GetHashCode

后端 未结 6 1541
-上瘾入骨i
-上瘾入骨i 2020-12-31 11:01

Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn\'t easily edit class implementations of object being compared, I went with the fol

6条回答
  •  一个人的身影
    2020-12-31 11:35

    Try this code:

    public class GenericCompare : IEqualityComparer where T : class
    {
        private Func _expr { get; set; }
        public GenericCompare(Func expr)
        {
            this._expr = expr;
        }
        public bool Equals(T x, T y)
        {
            var first = _expr.Invoke(x);
            var sec = _expr.Invoke(y);
            if (first != null && first.Equals(sec))
                return true;
            else
                return false;
        }
        public int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }
    }
    

    Example: collection = collection.Except(ExistedDataEles, new GenericCompare(x=>x.Id)).ToList();

提交回复
热议问题