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

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

假设我有以下对象

  1. public class DepartmentSchema
  2. {
  3. public int Parent { get; set; }
  4. public int Child { get; set; }
  5. }

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

  1. Parent | Child
  2. ---------------
  3. 4 | 1
  4. 8 | 4
  5. 5 | 7
  6. 4 | 2
  7. 8 | 4
  8. 4 | 1

我想对所有具有相同父值和子值的对象进行分组。分组后,我希望得到以下列表

  1. Parent | Child
  2. ---------------
  3. 4 | 1
  4. 8 | 4
  5. 5 | 7
  6. 4 | 2

我设法使用IGrouping获得成功=〉
departmentSchema.GroupBy(x => new { x.Parent, x.Child }).ToList();
但结果是List<IGrouping<'a,DepartmentSchema>>而不是List<DepartmentSchema>
我知道我可以创建一个新的foreach循环,并从组列表中创建一个新的List<DepartmentSchema>,但我想知道是否有更好的方法
先谢了

bzzcjhmw

bzzcjhmw1#

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

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

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

相关问题