如何在linq中汇总一个子列表?

编程入门 行业动态 更新时间:2024-10-26 03:35:02
本文介绍了如何在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中汇总一个子列表?

本文发布于:2023-11-22 07:02:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616424.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:个子   如何在   列表   linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!