Girish Mahida
Girish Mahida

Reputation: 85

Group by List using inner list

Below is my List collection.

public class A
{
    public String id{ get; set; }
    public string name{ get; set; }
    public List<B> nestedList { get; set; }
}
public class B
{
    public String innerid{ get; set; }
    public string innername { get; set; }
}

I want to use group by on nested collection properties So I can have output as

  innerid="1",
  innername="Name1",
    {
      id= "1", name= "One"
      id= "2", name= "Two"
      id= "4", name= "Four"
    }
  innerid="2",
  innername="Name2",
    {
      id= "3", name= "Three"
      id= "6", name= "Six"
      id= "8", name= "Eight"
    }

I tried .GroupBy(a => a.nestedList.First().innerid).ToList() But I am not getting required output.

Upvotes: 0

Views: 2886

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460380

You want to reverse the hierarchy, so grouping by the nested-B and list the parent-A as children?

var groups = aList
   .SelectMany(a => a.nestedList.Select(b => new { A = a, B = b }))
   .GroupBy(x => new { x.B.innerid, x.B.innername })
   .Select(g => new { 
       g.Key.innerid, 
       g.Key.innername, 
       aItems = g.Select(x => new { x.A.id, x.A.name }) 
    });

Instead of selecting anonymous types you can also select the original A and B instances.

Upvotes: 3

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250406

Assuming the items from the result must contain items of type A, you could use query syntax to solve this:

 var grouping = from a in collectionOfA
                from b in a.nestedList
                group a by new { b.innerid, b.innername } into g
                select new
                {
                    innerid = g.Key.innerid,
                    innername = g.Key.innername,
                    items = g.ToList()
                };

Upvotes: 1

Related Questions