Group nested list with linq

10,940

Solution 1

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();

Solution 2

SelectMany takes an IEnumerable<SomethingWithAnIEnumerable> and flattens all the SomethingWithAnIEnumerable's selected IEnumerables into a single IEnumerable:

nestedList = groupedData.SelectMany(pa => pa.nestedList).ToList()

Solution 3

use SelectMany

if you want to group the list into one use

nestedList = groupedData.SelectMany(d=>d.nestedList)

and if you want Sum of that list, use

nestedList = groupedData.SelectMany(d=>d.nestedList).Sum(o=>o.otherNumber)
Share:
10,940
Sergej Popov
Author by

Sergej Popov

SOreadytohelp

Updated on June 18, 2022

Comments

  • Sergej Popov
    Sergej Popov almost 2 years

    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();
    
  • sloth
    sloth over 11 years
    I think the Sum part is wrong here. I admit that the question is not exactly clear since the OP said HOW TO SUM/GROUP NESTED PART?, but TypeA.nestedList is of type List<TypeB> and not int.
  • Sergej Popov
    Sergej Popov over 11 years
    Yes, that's the one, Thanks!!