How do I sum a sub-list in linq?

旧时模样 提交于 2020-12-01 10:47:37

问题


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

I have:

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

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

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) .%>

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?


回答1:


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) %>

Here's how this works

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

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)

This just sums the TotalUnits member of List2.

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;}



回答2:


If I understand you correctly, you're looking for something like this:

Model.List1.Where(x => x.List2.Any()).Select(x => x.List2.Sum(y => y.TotalUnits))

This will give you a list of sums of the sublists that contain elements.



来源:https://stackoverflow.com/questions/4138866/how-do-i-sum-a-sub-list-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!