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?
In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.
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;}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With