C#如何按具有相同属性值的对象对List进行分组

时间:2018-03-24 14:29:24

标签: c# linq

假设我有以下对象

 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 =&gt;

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

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

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

提前致谢

1 个答案:

答案 0 :(得分:4)

因为你想要的是每个组中的一个元素,所以只需选择它们:

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

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

LINQ's Distinct() on a particular property