简体   繁体   中英

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 were List<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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM