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();

  • 相关阅读:
    正向代理和反向代理
    轮询和长轮询
    偏函数 方法与函数的区别
    pipreqs 生成项目依赖的第三方包
    git安装与使用
    自动生成接口文档
    上线
    Android APK加固-完善内存dex
    Android APK加固-内存加载dex
    替换ClassLoader
  • 原文地址:https://www.cnblogs.com/CodeSnippet/p/8670764.html
Copyright © 2011-2022 走看看