Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum a sub-list in linq?

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?

like image 208
chum of chance Avatar asked Nov 09 '10 21:11

chum of chance


People also ask

How to sum amount in linq?

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#.


2 Answers

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;}
like image 195
JaredPar Avatar answered Sep 19 '22 12:09

JaredPar


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.

like image 24
recursive Avatar answered Sep 20 '22 12:09

recursive