zoukankan      html  css  js  c++  java
  • C#-Linq扩展方法DistinctBy

    public static class LinqExtensions
        {
            public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, System.Func<T, TKey> property)
            {
                GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T, TKey>(property);
                return items.Distinct(comparer);
            }
        }
        public class GeneralPropertyComparer<T, TKey> : IEqualityComparer<T>
        {
            private System.Func<T, TKey> expr { get; set; }
            public GeneralPropertyComparer(System.Func<T, TKey> expr)
            {
                this.expr = expr;
            }
            public bool Equals(T left, T right)
            {
                var leftProp = expr.Invoke(left);
                var rightProp = expr.Invoke(right);
                if (leftProp == null && rightProp == null)
                    return true;
                else if (leftProp == null ^ rightProp == null)
                    return false;
                else
                    return leftProp.Equals(rightProp);
            }
            public int GetHashCode(T obj)
            {
                var prop = expr.Invoke(obj);
                return (prop == null) ? 0 : prop.GetHashCode();
            }
        }

    自带的Distinct能做的事比较简单,对比集合中的Object的Hash值来去重

    很多时候我们需要的是根据Object中的某个字段值来做去重,比如Student.Name

    那么自带的Distinct就要自己实现一个Comparer了

    找了很多资料,发现有前人种下了这棵树,分享出来。

    Usage:{Linq代码}.DistinctBy(Student.Name).ToList();

  • 相关阅读:
    java学习笔记(四)
    Sigmoid 函数
    Neural Architectures for Named Entity Recognition 学习笔记
    java学习笔记(三)
    java学习笔记(二)
    Java学习笔记(一)
    shell 小技巧
    Network Embedding 相关论文
    C++学习笔记(二)
    js判断某字符出现的个数
  • 原文地址:https://www.cnblogs.com/CodeSnippet/p/8670764.html
Copyright © 2011-2022 走看看