【问题标题】:C# how to group List by objects with the same property valuesC#如何按具有相同属性值的对象对列表进行分组
【发布时间】:2018-03-24 14:29:23
【问题描述】:

假设我有以下对象

 public class DepartmentSchema
{
    public int Parent { get; set; }
    public int Child { get; set; }
}

我有一个List<DepartmentSchema>,结果如下:

Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2
  8    |   4
  4    |   1

我想将所有具有相同父值和子值的对象分组 分组后我想要的结果是以下列表

 Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2

我成功使用 IGrouping =>

departmentSchema.GroupBy(x => new { x.Parent, x.Child }).ToList();

但结果是List<IGrouping<'a,DepartmentSchema>> 而不是List<DepartmentSchema>

我知道我可以创建一个新的 foreach 循环并从组列表中创建一个新的List<DepartmentSchema>,但我想知道是否有更好的方法

提前致谢

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    由于您想要的是每个组中的一个元素,因此只需选择它们:

    departmentSchema
      .GroupBy(x => new { x.Parent, x.Child })
      .Select(g => g.First())
      .ToList(); 
    

    但是,由于您真正要做的是制作一个不同元素的列表,我认为您真正想要的序列运算符是 Jon 的DistinctBy。在这里阅读:

    LINQ's Distinct() on a particular property

    【讨论】:

    • 是的,这就解决了问题。谢谢埃里克
    猜你喜欢
    • 2018-10-24
    • 2021-02-05
    • 2020-04-24
    • 2022-01-21
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    相关资源
    最近更新 更多