zoukankan      html  css  js  c++  java
  • 如何很好的使用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);

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

    List<Person> distinctPeople = allPeople
      .GroupBy(p => new {p.Id, p.Name} )
      .Select(g => g.First())
      .ToList();

    以上,您觉得哪种方案更好一些呢?个人最偏向于第二种用法,您呢?

  • 相关阅读:
    nacos 命名空间
    Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences
    gitee
    maven引入junit 4.12,项目import org.junit.Test 还是报错.
    gitflow
    202011
    idea 忽略显示不需要的文件
    服务熔断 & 降级区别
    各种微服务框架对比
    zookeeper not connected
  • 原文地址:https://www.cnblogs.com/sylone/p/6094724.html
Copyright © 2011-2022 走看看