views:

677

answers:

3

Hi, 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...?

+1  A: 
Richard
+7  A: 

I think this might work:

from p in m.Items
group p by p.Id into g
select new { SumTotal = g.Sum(x => x.Total), SumDone = g.Sum(x => x.Done) }
Steven
Or when Item has no unique identifier, you could write `group p by p into g`.
Steven
That did the trick, albeit with a modification:from p in m.Itemsgroup p by p.Id into gselect new { SumTotal = g.Sum(r => r.Total), SumDone = g.Sum(r => r.Done) }
Axarydax
You're right, `p` was already used in the query. Fixed it.
Steven
A: 

How about

   m.Items.Select(item => new { Total = item.Total, Done = item.Done })
          .Aggregate((t1, t2) => new { Total = t1.Total + t2.Total, Done = t1.Done + t2.Done });
Jens