Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#如何按具有相同属性值的对象对列表进行分组_C#_Linq - Fatal编程技术网

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
。请在此处阅读:


是的,这就解决了问题。谢谢你,埃里克