Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum column with linq to sql

Tags:

c#

linq-to-sql

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

like image 564
Rod Avatar asked Nov 16 '09 20:11

Rod


1 Answers

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.

like image 77
Justin Niessner Avatar answered Sep 30 '22 15:09

Justin Niessner