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

qltillow  于 2022-12-06  发布在  C#
关注(0)|答案(1)|浏览(145)

假设我有以下对象

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>,但我想知道是否有更好的方法
先谢了

bzzcjhmw

bzzcjhmw1#

由于您需要的是每个组中的一个元素,因此只需将其选中即可:

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

然而,由于您 * 真正 * 做的是 * 创建一个 * 不同元素 * 的列表,我认为您真正需要的序列操作符是Jon的DistinctBy
LINQ's Distinct() on a particular property

相关问题