zoukankan      html  css  js  c++  java
  • 解决c#distinct不好用的问题

    当一个结合中想根据某一个字段做去重方法时使用以下代码

    IQueryable 继承自IEnumerable

    先举例:

    #region linq to object 
    List<People> peopleList = new List<People>();
    peopleList.Add(new People { UserName = "zzl", Email = "1" });
    peopleList.Add(new People { UserName = "zzl", Email = "1" });
    peopleList.Add(new People { UserName = "lr", Email = "2" });
    peopleList.Add(new People { UserName = "lr", Email = "2" });
    
    Console.WriteLine("用扩展方法可以过滤某个字段,然后把当前实体输出");
    peopleList.DistinctBy(i => new { i.UserName }).ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email));
    Console.WriteLine("默认方法,集合中有多个字段,当所有字段发生重复时,distinct生效,这与SQLSERVER相同");
    peopleList.Select(i => new { UserName = i.UserName, Email = i.Email }).OrderByDescending(k => k.Email).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email));
    Console.WriteLine("集合中有一个字段,将这个字段重复的过滤,并输出这个字段");
    peopleList.Select(i => new { i.UserName }).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName));
    
    #endregion

    该扩展方法贴出:

    public static class EnumerableExtensions
    {
      public static IEnumerable<TSource> DistinctBy<TSource, Tkey>(this IEnumerable<TSource> source, Func<TSource, Tkey> keySelector)
        {
          HashSet<Tkey> hashSet = new HashSet<Tkey>();
          foreach (TSource item in source)
          {
            if (hashSet.Add(keySelector(item)))
            {
              yield return item;
            }
          }
         }
    }
    萌橙 你瞅啥?
  • 相关阅读:
    源码篇:Python 实战案例----银行系统
    源码分享篇:使用Python进行QQ批量登录
    python制作电脑定时关机办公神器,另含其它两种方式,无需编程!
    Newtonsoft.Json 去掉
    C#Listview添加数据,选中最后一行,滚屏
    C# 6.0语法糖
    XmlHelper
    AppSettings操作类
    JsonHelper
    JS加载获取父窗体传递的参数
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/10971869.html
Copyright © 2011-2022 走看看