Reputation: 5624
I have a List<A>
. Each A
has a List<B>
where B
has an int x
. I am trying to calculate the average value of x
for all A
.
I have tried:
@Model.AList.ForEach(a => a.BList.Average(b => b.x))
This complains about missing a return value. I've experimented with something like:
@Model.Alist.ForEach(a =>
{
return a.Blist.Average(b => b.x);
})
But this is incorrect syntax since ForEach
expects void return.
How can I calculate the average value of x
for all A
usin a LINQ query?
Upvotes: 0
Views: 548
Reputation: 3214
I'm not sure if you mean you want the different averages for each BList, so here's that solution:
@Model.AList.Select(a => a.BList.Average(b => b.x))
Upvotes: 1
Reputation: 218867
First flatten the collection, then take the average. Something like this:
@Model.AList.SelectMany(a => a.BList).Average(b => b.x)
Upvotes: 7