C# 对象列表 List 去重

 public class Compare<T, C> : IEqualityComparer<T>
    {
        private Func<T, C> _getField;
        public Compare(Func<T, C> getfield)
        {
            _getField = getfield;
        }
        public bool Equals(T x, T y)
        {
            return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
        }
        public int GetHashCode(T obj)
        {
            return EqualityComparer<C>.Default.GetHashCode(_getField(obj));
        }
    }


public static class ObjectExtensions
    {    
    public static IEnumerable<T> DistinctBy<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
        {
            return source.Distinct(new Compare<T, C>(getfield));
        }
    }


list.DistinctBy(e => e.Id).ToList();

 

posted @ 2020-08-04 14:35  wfpanskxin  阅读(1041)  评论(0编辑  收藏  举报