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 方法,并且性能也更加好

posted @   祝融6X  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示