自定义通用Distinct去除重复数据的2中方式

由于Lambda Distinct方法默认是按照集合里面的值比较的,所以当集合里面存放的是类的时候,我们一般是按照实体中的某一属性值比较,其实是用默认的Distinct也可以的,自己先定义一个实现了接口IEqualityComparer的类,然后调用Distinct的重载将这个类传递进去,但是这样太麻烦了,而且不能重用 所以参考了一些资料 整了一个程序员最爱的通用的方法

A、通过实现接口IEqualityComparer来实现此需求

代码如下:

1、先定义比较类实现IEqualityComparer

    public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;
        private IEqualityComparer<V> comparer;
        public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer)
        {
            this.keySelector = keySelector;
            this.comparer = comparer;
        }
        public CommonEqualityComparer(Func<T, V> keySelector)
            : this(keySelector, EqualityComparer<V>.Default)
        { }
        public bool Equals(T x, T y)
        {
            return comparer.Equals(keySelector(x), keySelector(y));
        }
        public int GetHashCode(T obj)
        {
            return comparer.GetHashCode(keySelector(obj));
        }
    }

2、接下来扩展Distinct 实现针对实体类的属性Distinct的重载方法

public static class DistinctExtensions
    {
        public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
        {
            return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
        }
        public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector, IEqualityComparer<V> comparer)
        {
            return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer));
        }
    }

ok完毕,

测试数据:

List<SalesOrder> lists = new List<SalesOrder>() {
new SalesOrder(){SalesOrderNo="aaa"},
new SalesOrder(){SalesOrderNo="bbb"},
new SalesOrder(){SalesOrderNo="aaa"},
new SalesOrder()
};

var item= lists.Distinct(m => m.SalesOrderNo);

B、通过HashSet来实现 ,个人来说更喜欢第二种,虽然短小但是精悍

因为HashSet的值是不允许重复的,当你通过Add方法为HashSet添加值的时候,如果已经存在该值则会返回false,

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

 

完结!thank for you 

posted @ 2014-11-11 17:56  程序有Bug  阅读(1353)  评论(0编辑  收藏  举报