Search code examples
c#linq

C# how to group List by objects with the same property values


assume I have the following object

 public class DepartmentSchema
{
    public int Parent { get; set; }
    public int Child { get; set; }
}

and I have a List<DepartmentSchema> with the following results:

Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2
  8    |   4
  4    |   1

I want to group all the objects that has the same parent value AND child value After the grouping what I want in result is the following list

 Parent | Child
---------------
  4    |   1
  8    |   4
  5    |   7
  4    |   2

I manage to success using IGrouping =>

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

but the result wereList<IGrouping<'a,DepartmentSchema>> instead of List<DepartmentSchema>

I know I can make a new foreach loop and create a new List<DepartmentSchema> from the group list but I wonder if there is any better way

Thanks in advance


Solution

  • Since what you want is one element from each group, just select them out:

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

    However, since what you are really doing is making a list of distinct elements, I think the sequence operator you really want is Jon's DistinctBy. Read about that here:

    LINQ's Distinct() on a particular property