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?
Are you trying to get the sum of all of the
TotalUnitsin everyList2instance? If so then do the followingHere’s how this works
This takes the
List<List1>and transforms it into anIEnumerable<List2>.SelectManyis similar toSelectin 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.This just sums the
TotalUnitsmember ofList2.There is also a small typo in your code. I believe it should read as follows (note the missing
classkeyword)