How to use the IEqualityComparer

前端 未结 6 1904
一向
一向 2020-11-27 04:36

I have some bells in my database with the same number. I want to get all of them without duplication. I created a compare class to do this work, but the execution of the fun

6条回答
  •  一个人的身影
    2020-11-27 04:58

    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 of its use would be

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

提交回复
热议问题