Reputation: 673
I have a list that contain following type of objects
public class A {
public List<B> B {get;set;}
}
The B class
state as follows.
public class B {
public List <C> C { get;set;}
}
The C class
state as follows.
public class C {
public int Id { get ; set ;}
public string Name { get; set;}
}
Can someone point me how can I group above list by Name
property in C
class.
Upvotes: 0
Views: 1388
Reputation: 16991
var results = a.SelectMany(a1 => a1.B.SelectMany(b1 => b1.C)
.GroupBy(g => g.Name)
.Select(g => new { Name = g.Key, Count = g.Count() }));
It should return a list of objects containing a Name
property for each unique name found, along with a Count
property specifying how many of that Name
were grouped.
The nested calls to SelectMany
will flatten the object hierarchy, the GroupBy
will create the grouping on the Name
property. Finally, a new anonymous type List is returned though the Select
and is populated with properties from the group, with g.Key
being the value the grouping was based on (C.Name
).
A Fiddle can be found Here (Provided by @chadalavada harish)
Upvotes: 2