原创

c# 中linq DISTINCT去重方法

dbBeforeEntityList为数据list,得到的query是经过求和和分组的,但是还是满足不了需求,因为sql中有DISTINCT方法,所以搜到linq也是有去重方法,但是,linq不是很智能,需要自定义来去重

  var query = from c in dbBeforeEntityList
                        group c by new
                        {
                            c.fequkey,
                            c.fyear
                        }
         into s
                        select new
                        {
                            fyear = s.Select(m => m.fyear),
                            fequkey = s.Select(m => m.fequkey),
                            fcount = s.Sum(p => long.Parse(p.fcount))

                        };
            var result = query.Distinct(p => p.fyear);

以上就按照自己的需求的来写,下面去重的自定义方法是通用的,不需要再有变动,直接粘贴使用即可。

  public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
    {
        private Func<T, V> keySelector;

        public CommonEqualityComparer(Func<T, V> keySelector)
        {
            this.keySelector = keySelector;
        }

        public bool Equals(T x, T y)
        {
            return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
        }

        public int GetHashCode(T obj)
        {
            return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
        }
    }
    //linq 的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));
        }
    }
正文到此结束
本文目录