Group nested list with linq

c#, group-by, linq, list

Solution

I think that this will resolve your issue.

List<TypeA> list = TypeAList
    .GroupBy(a => a.identifierA)
    .Select(
        g =>
        new TypeA
            {
                identifierA = g.Key,
                number = g.Sum(n => n.number),
                nestedList =
                    g.SelectMany(l => l.nestedList)
                    .GroupBy(b => b.identifierB)
                    .Select(
                        gg =>
                        new TypeB
                            {
                                identifierB = gg.Key,
                                otherNumber = gg.Sum(b => b.otherNumber)
                            }).ToList()
            }).ToList();

Problem

I have a nested list of objects. That I need to group by `identifierA` and `Sum` its numeric properties, nested list shall group respectively: ``` public class TypeA { public String identifierA{ get; set; } public Int32 number { get; set; } public List<TypeB> nestedList { get; set; } } public class TypeB { public String identifierB { get; set; } public Int32 otherNumber { get; set; } } ``` So I'm expecting something like this: ``` var List<TypeA> groupedList = (from a in TypeAList group a by a.identifierA into groupedData select new TypeA { identifierA = groupedData.Key, number = groupedData.Sum(g => g.number ), nestedList = //HOW TO GROUP NESTED PART? }).ToList(); ```

Original source