2

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

JRB
  • 1,943
  • 1
  • 10
  • 9
riv
  • 93
  • 1
  • 11

1 Answers1

7

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

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067