C#如何按具有相同属性值的对象对列表进行分组
假设我有以下对象C#如何按具有相同属性值的对象对列表进行分组,c#,linq,C#,Linq,假设我有以下对象 public class DepartmentSchema { public int Parent { get; set; } public int Child { get; set; } } 我有一个列表,结果如下: Parent | Child --------------- 4 | 1 8 | 4 5 | 7 4 | 2 8 | 4 4 | 1 我想对所有具有相同父值
public class DepartmentSchema
{
public int Parent { get; set; }
public int Child { get; set; }
}
我有一个列表
,结果如下:
Parent | Child
---------------
4 | 1
8 | 4
5 | 7
4 | 2
8 | 4
4 | 1
我想对所有具有相同父值和子值的对象进行分组
在分组之后,我想要的结果是下面的列表
Parent | Child
---------------
4 | 1
8 | 4
5 | 7
4 | 2
我使用iGroup=>
departmentSchema.GroupBy(x=>new{x.Parent,x.Child}).ToList()代码>
但是结果是List,因为您需要的是每组中的一个元素,只需将它们选出来:
departmentSchema
.GroupBy(x => new { x.Parent, x.Child })
.Select(g => g.First())
.ToList();
但是,由于您真正要做的是列出不同的元素,因此我认为您真正需要的序列运算符是Jon的DistinctBy
。请在此处阅读:
是的,这就解决了问题。谢谢你,埃里克