Reputation: 6300
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?
Upvotes: 9
Views: 9404
Reputation: 755587
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;}
Upvotes: 18
Reputation: 86172
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.
Upvotes: 2