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

IQueryable 继承自IEnumerable

先举例:

#region linq to object
List<People> peopleList = new List<People>();
peopleList.Add(new People { UserName = "zzl", Email = "" });
peopleList.Add(new People { UserName = "zzl", Email = "" });
peopleList.Add(new People { UserName = "lr", Email = "" });
peopleList.Add(new People { UserName = "lr", Email = "" }); 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;
        }
      }
     }
}

最新文章

  1. java基础--java.util.Date类型小结
  2. HDU 4686 Arc of Dream(快速幂矩阵)
  3. A Study of WebRTC Security
  4. iOS核心动画学习整理
  5. [Android UI] ProgressBar自定义
  6. 02---Net基础加强
  7. PERL 学习
  8. Coursera机器学习课程(2016 )错题集
  9. SQL语句一些特殊的用法
  10. OC-之AFNetworking
  11. java 对象的组合,一个类组合到另一个类中(例如手机卡装到手机上)
  12. curl通过调用WebService查询当前天气
  13. cve-2017-8464 复现 快捷方式远程代码执行
  14. 34.Linux-printk分析、使用prink调试驱动
  15. unittest单元测试框架详解
  16. HDU 1039(字符串判断 **)
  17. ReactNative 常见红屏黄屏及终端报错
  18. 微服务架构集大成者—Spring Cloud (转载)
  19. 量身打造自己的MyEclipse(多图)
  20. 【转】基于easyui开发Web版Activiti流程定制器详解(一)——目录结构

热门文章

  1. 【AMAD】dramatiq -- Python3实现的一个快速的,可信赖的分布式任务处理库
  2. 如何解决Oracle11g使用dmp命令无法导出空表问题
  3. 小菜鸟之java内存结构
  4. 常用的 Git 命令,给你准备好了!
  5. Python和其他编程语言
  6. vue-router和webpack懒加载,页面性能优化篇
  7. redis 学习(13)-- BitMap
  8. 关于mysql-5.7.13-winx64服务无法启动的解决方法
  9. 安装kubuctl
  10. selenium自动化测试工具模拟登陆爬取当当网top500畅销书单