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 IEnumerable
s 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)
Comments
-
Sergej Popov almost 2 years
I have a nested list of objects. That I need to group by
identifierA
andSum
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 over 11 yearsI 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?, butTypeA.nestedList
is of typeList<TypeB>
and notint
. -
Sergej Popov over 11 yearsYes, that's the one, Thanks!!