如何在linq中汇总一个子列表? [英] How do I sum a sub-list in linq?

查看:93
本文介绍了如何在linq中汇总一个子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对列表的子列表上的一个属性求和...例如:

I would like sum a property on a sub list of a list ... example:

我有:

public class List1 {
public List<List2> List2 { get; set; }
}

public class List2 {
public int TotalUnits { get; set; }
}

在我看来,我有一个 List< List1> ,所以我想做类似的事情:

In my view I have a List<List1>, so that I want to do something like:

<%= Model.List1.Where(x.List2.Any()).Sum(x=>x.TotalUnits) .%>

很明显,Sum之后的所有操作都不起作用,但是有没有办法我可以在一行中执行此操作而不必在服务器端创建新的Dto?

Obviously everything after Sum doesn't work, but is there a way I can do this in a single line without having to create a new Dto on my server side?

推荐答案

您是否要获取每个 List2 实例中所有 TotalUnits 的总和?如果是这样,请执行以下操作

Are you trying to get the sum of all of the TotalUnits in every List2 instance? If so then do the following

<%= Model.List1.SelectMany(x => x.List2).Sum(x => x.TotalUnits) %>

这是它的工作原理

Model.List1.SelectMany(x => x.List2)

这采用了 List< List1> 并将其转换为 IEnumerable< List2> . SelectMany Select 相似,因为它是枚举中元素的投影,但它期望得到可枚举的结果.然后将可枚举结果的集合放入单个可枚举中.或者用简单的话来说,它使列表列表变平.

This takes the List<List1> and transforms it into an IEnumerable<List2>. SelectMany is similar to Select in that it's a projection for elements in an enumeration except that it expects an enumerable result. The collection of enumerable results is then put into a single enumerable. Or in simpler words, it flattens a list of lists.

.Sum(x => x.TotalUnits)

这只是对 List2 TotalUnits 成员求和.

您的代码中还有一个小的错字.我认为它应如下所示(请注意缺少的 class 关键字)

There is also a small typo in your code. I believe it should read as follows (note the missing class keyword)

public int TotalUnits { get; set;}

这篇关于如何在linq中汇总一个子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆