解决c#distinct不好用的问题
2024-09-05 12:55:37
当一个结合中想根据某一个字段做去重方法时使用以下代码
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;
}
}
}
}
最新文章
- java基础--java.util.Date类型小结
- HDU 4686 Arc of Dream(快速幂矩阵)
- A Study of WebRTC Security
- iOS核心动画学习整理
- [Android UI] ProgressBar自定义
- 02---Net基础加强
- PERL 学习
- Coursera机器学习课程(2016 )错题集
- SQL语句一些特殊的用法
- OC-之AFNetworking
- java 对象的组合,一个类组合到另一个类中(例如手机卡装到手机上)
- curl通过调用WebService查询当前天气
- cve-2017-8464 复现 快捷方式远程代码执行
- 34.Linux-printk分析、使用prink调试驱动
- unittest单元测试框架详解
- HDU 1039(字符串判断 **)
- ReactNative 常见红屏黄屏及终端报错
- 微服务架构集大成者—Spring Cloud (转载)
- 量身打造自己的MyEclipse(多图)
- 【转】基于easyui开发Web版Activiti流程定制器详解(一)——目录结构