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

  • 相关阅读:
    python 多线程测试
    python 多线程join()
    python 多线程 t.setDaemon(True):
    线程锁
    python 多线程
    模板渲染和参数传递.
    求两个数组的交集
    java数组并集/交集/差集(补集)
    java各种集合的线程安全
    页面跳转和重定向
  • 原文地址:https://www.cnblogs.com/CodeSnippet/p/8670764.html
Copyright © 2011-2022 走看看