简体   繁体   English

Linq列表的平均值及其所有嵌套列表值

[英]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 . 我正在尝试计算所有Ax的平均值。

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查询中计算所有Ax的平均值?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM