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

riv*_*riv 2 c# linq

假设我有以下对象

 public class DepartmentSchema
{
    public int Parent { get; set; }
    public int Child { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有List<DepartmentSchema>以下结果:

Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2
  8    |   4
  4    |   1
Run Code Online (Sandbox Code Playgroud)

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

 Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2
Run Code Online (Sandbox Code Playgroud)

我成功使用 IGrouping =>

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

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

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

提前致谢

Eri*_*ert 5

由于您想要的是每组中的一个元素,只需将它们选中即可:

departmentSchema
  .GroupBy(x => new { x.Parent, x.Child })
  .Select(g => g.First())
  .ToList(); 
Run Code Online (Sandbox Code Playgroud)

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

LINQ 对特定属性的 Distinct()