[英]Linq average of list with all its nested list values
I have a List<A>
. 我有一个
List<A>
。 Each A
has a List<B>
where B
has an int x
. 每个
A
具有一个List<B>
,其中B
具有一个int x
。 I am trying to calculate the average value of x
for all A
. 我正在尝试计算所有
A
的x
的平均值。
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. 但这是不正确的语法,因为
ForEach
期望返回空值。
How can I calculate the average value of x
for all A
usin a LINQ query? 如何在LINQ查询中计算所有
A
的x
的平均值?
First flatten the collection, then take the average. 首先展平集合,然后取平均值。 Something like this:
像这样:
@Model.AList.SelectMany(a => a.BList).Average(b => b.x)
我不确定您是否要为每个BList均设置不同的平均值,所以这是解决方案:
@Model.AList.Select(a => a.BList.Average(b => b.x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.