博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决c#distinct不好用的问题
阅读量:4311 次
发布时间:2019-06-06

本文共 1463 字,大约阅读时间需要 4 分钟。

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

IQueryable 继承自IEnumerable

先举例:

#region linq to object List
peopleList = new List
();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
DistinctBy
(this IEnumerable
source, Func
keySelector)    {      HashSet
hashSet = new HashSet
();      foreach (TSource item in source)      {        if (hashSet.Add(keySelector(item)))        {          yield return item;        }      }     }}

 

转载于:https://www.cnblogs.com/daimaxuejia/p/10971869.html

你可能感兴趣的文章
tcp/udp协议代码实现
查看>>
python---django中orm的使用(2)
查看>>
读书时间《JavaScript高级程序设计》四:BOM,客户端检测
查看>>
Linux基础命令---free显示内存使用
查看>>
转:CentOS---网络配置详解
查看>>
绕任意单位轴旋转矩阵计算
查看>>
洛谷P2502[HAOI2006]旅行
查看>>
Linux 配置mail发送邮件
查看>>
Linux 正则
查看>>
织梦网站搬家,数据库无法导入的解决方法
查看>>
线程基础知识归纳
查看>>
CArray 的两种方式与类中包含指针情况
查看>>
ElasticSearch 自定义排序处理
查看>>
域的建立过程
查看>>
使用installer安装kbengine
查看>>
IOS 开发didFinishLaunchingWithOptions 设置启动View
查看>>
MyBank(自助银行)
查看>>
python机器学习-sklearn挖掘乳腺癌细胞(二)
查看>>
javascript中的函数节流和函数去抖
查看>>
异步函数的串行执行和并行执行
查看>>