• DistinctBy


    如何很好的使用Linq的Distinct方法[全屏看文]

    Person1: Id=1, Name="Test1"
    Person2: Id=1, Name="Test1"
    Person3: Id=2, Name="Test2"

    以上list如果直接使用distinct方法进行过滤,仍然返回3条数据,而需要的结果是2条数据。下面给出解这个问题的方法:


    方法1: Distinct 方法中使用的相等比较器。这个比较器需要重写Equals和GetHashCode方法,个人不推荐,感觉较麻烦,需要些多余的类,并且用起来还要实例化一个比较器,当然自己也可以写一个泛型的比较器生成工厂用来专门生成比较器,但仍然觉得较麻烦。

                  MSDN给出的做法,具体参照:http://msdn.microsoft.com/zh-cn/library/bb338049.aspx


    方法2:自己扩展一个DistinctBy。这个扩展方法还是很不错的,用起来很简洁,适合为框架添加的Distinct扩展方法。

    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;
            }
        }
    }

    使用方法如下(针对ID,和Name进行Distinct):

    var query = people.DistinctBy(p => new { p.Id, p.Name });

    若仅仅针对ID进行distinct:

    var query = people.DistinctBy(p => p.Id);

    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;
            }
        }
    }

    方法3:通过GroupBy分组后,并取出第一条数据。简单易用,很方便。这是一种迂回策略,代码理解起来没有Distinct表意清晰,虽然实现了效果。

    List<Person> distinctPeople = allPeople
      .GroupBy(p => new {p.Id, p.Name} )
      .Select(g => g.First())
      .ToList();
  • 相关阅读:
    解决WPF中异常导致的程序Crash
    Python---pep8规范
    Python---13面向对象编程
    Python---12函数式编程------12.3匿名函数&装饰器&偏函数
    Python---12函数式编程------12.2返回函数
    Python中*args和**kwargs的区别
    测试干货-接口测试(接口测试工具+接口测试用例)
    Python---13靠谱的Pycharm安装详细教程
    Python---12函数式编程------12.1高阶函数
    Python---11模块
  • 原文地址:https://www.cnblogs.com/zhangxiaolei521/p/5234939.html
Copyright © 2020-2023  润新知