Linq下的distinct()比SQLServer下的distinct更强大,更自由,呵呵
大家好,今天调点时间来说一下LINQ里的distinct(),以及解决过滤重复记录的方法
准备数据:先来个实体类,自己为它赋值,然后用 linq to object对象它进行distinct的操作
public abstract class BaseEntity { public BaseEntity() : this(0) { } public BaseEntity(long id) { ID = id; } public long ID { get; private set; } } class People : BaseEntity { public string UserName { get; set; } public string Email { get; set; } public int Age { get; set; } }
#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![]()
下面我们来看一下linq to sql的测试情况,看代码:
#region 对linq to sql进行Ddistinct()
DataClasses1DataContext db = new DataClasses1DataContext(); Console.WriteLine("对单个字段可以实现"); db.Customer.Select(i => new { i.Name }).Distinct().ToList().ForEach(i => Console.WriteLine(i.Name)); Console.WriteLine("直接对原-数据集中多个字段进行过滤"); db.Customer.ToList().Select(i => new { Name = i.Name, Email = i.Email }).Distinct().ToList().ForEach(i => { Console.WriteLine(i.Name + i.Email); }); Console.WriteLine("将linq to sql对象赋给别一个实体对象时出现了不能过滤的问题"); List<Customermodel> entity = new List<Customermodel>(); db.Customer.ToList().Select(i => new { Name = i.Name, Email = i.Email }).ToList().ForEach(i => { entity.Add(new Customermodel { Name = i.Name, Email = i.Email }); }); entity.Distinct().ToList().ForEach(i => Console.WriteLine(i.Name + i.Email)); Console.WriteLine("使用distinct扩展方法进行过滤,没有问题"); entity.DistinctBy(j => new { j.Name }).ToList().ForEach(i => Console.WriteLine(i.Name + i.Email)); #endregion 测试结果:
最后,贡献出DistinctBy这个IEnumerable的扩展方法:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下