let's say that I have a table called Items (ID int, Done int, Total int)
I can do it by two queries:
int total = m.Items.Sum(p=>p.Total)
int done = m.Items.Sum(p=>p.Done)
But I'd like to do it in one query, something like this:
var x = from p in m.Items select new { Sum(p.Total), Sum(p.Done)};
Surely there is a way to call aggregate functions from LINQ syntax...?
To sum the table, group by a constant:
Figuring out where to extract the sums or other aggregate in the rest of my code confused me, until I remembered that the variable I constructed was an Iqueryable. Suppose we have a table in our database composed of Orders, and we want to produce a summary for the ABC company:
Now the fun part -- tempPrice and tempQty aren't declared anywhere but they must be part of myResult, no? Access them as follows:
A number of other Queryable methods could be used as well.
With a helper tuple class, either your own or—in .NET 4—the standard ones you can do this:
And
res.Item1
is the total of theTotal
column andres.Item2
of theDone
column.When you use group by Linq creates a new collection of items so you have two collections of items.
Here's a solution to both problems:
Code:
Here's the way you have to do the summation:
Here's a general example:
as you can see
This has been answered already, but the other answers will still do multiple iterations over the collection (multiple calls to Sum) or create lots of intermediate objects/Tuples which may be fine, but if it isn't, then you can create an extension method (or multiple) that does it the old-fashioned way but fits well in a LINQ expression.
Such an extension method would look like this:
And you can use it like this: