How to aggregate in a LINQ query

  • Thread starter Thread starter Paolo
  • Start date Start date
P

Paolo

I have a LINQ query which returns a sequence of rows all of which contains a
decimal field (T_Amount) e.g.

var trans =
from trans in dataSet.Transaction
where .... (filters)
....
select new
{
trans.T_Date,
p.P_Name,
c.C_Description,
s.S_Description,
pm.Value,
trans.T_Amount <<<< want to sum on this
};

I want to sum the values in T_Amount and show it in a label on a windows form.

I'd appreciate an example of how to construct such an aggregation, returning
the
total for sequence. I've done a fair amount of research but haven't found a
workable example.

Thanks
 
Pete: Thanks - yes, I've been poring over the Enumerable class and decided
Sum() was what I needed. I just didn't know how to express the code.

Now, where do I put decimal sum = trans.Sum(t => t.T_Amount); ?

If I put it after the select new {...}; statement I get "The name 'trans'
does not exist in the current context".

Peter Duniho said:
[...]
I want to sum the values in T_Amount and show it in a label on a windows
form.

I'd appreciate an example of how to construct such an aggregation,
returning the
total for sequence. I've done a fair amount of research but haven't
found a
workable example.

Did you look at the Enumerable.Sum<TSource>() method? Something like this:

decimal sum = trans.Sum(t => t.T_Amount);

Might do what you want.

Pete
 
Pete: thanks again. My original query variable was qryTrans. I must have
missed off the 'qry' bit when I cut and pasted the code. Anyway I've made
the change and it works perfectly.
 
Back
Top