tags:

views:

146

answers:

2

Hey all,

I have a DataView in which I would like to sum a column called "Amount"

Now I know I can iterate thru the columns and get the sum but I was wondering if is possible using Linq to Sql?

String sum = Linq to Sql stuff here (doesn't have to be a string, can be any type)

Thanks, rodchar

+1  A: 

Assuming the Amount column is a double (could be another type)

double sum = Table.Select(t => t.Amount ?? 0).Sum();

Or

double sum = Table.Sum(t => t.Amount ?? 0).Sum();

Using the null coelescing operator will give you a default of 0 if t.Amount is null.

Justin Niessner
This is what I had to do to get it to work: MyDataView.Table.Select().Select((t => Convert.ToDouble(t["amount"]))).Sum().ToString("c"); What if the amount is null? Would this be concern?
rod
I updated my answer to address null values.
Justin Niessner
Thank you and all for the help
rod
A: 

Excuse me for dataContext call syntax...

var sum = dataContext.Sum(x => x.Amount);

If you want to sum strings, you may want to use

var sum = string.Join(", ", dataContext.Select(x => x.StringColumn).ToArray());

Hope this works.

queen3