GroupBy与DistinctBy的区别和用法(System.Linq)
GroupBy
定义:对序列中的元素进行分组
返回:一个分组的集合,每个分组包含满足相同条件的元素
// Create a list of pets. List<Pet> pets = new List<Pet>{ new Pet { Name="Barley", Age=8 }, new Pet { Name="Boots", Age=4 }, new Pet { Name="Whiskers", Age=1 }, new Pet { Name="Daisy", Age=4 } }; // Group Pet.Age values by the Math.Floor of the age. // Then project an anonymous type from each group // that consists of the key, the count of the group's // elements, and the minimum and maximum age in the group. var query = petsList.GroupBy( pet => Math.Floor(pet.Age), pet => pet.Age, (baseAge, ages) => new { Key = baseAge, Count = ages.Count(), Min = ages.Min(), Max = ages.Max() });
DistinctBy
定义:主要用于在集合中根据某个属性去除重复项
返回:不包含重复值的无序序列,每个元素在指定属性上是唯一的
// Create a list of pets. var pets =new List<Pet>(); //去掉重复值 var query = pets .DistinctBy(ps=> new { ps.Name, ps.Age}).ToList();
二者区别
GroupBy
:分组操作,返回一个集合元素
DistinctBy
:去重操作,返回去重后的集合元素,简单有效去重方法
注意:但是如果需要使用到分组去重的操作,可以这样进行
var query= pets .GroupBy(ps => ps.Name) .Select(g => g.First()) .ToList();
GroupBy
通常结合Select
和 First
等方法来实现类似功能
如果仅仅是简单的操作推荐使用DistinctBy
方法,并且性能也更加好
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库