Reputation: 15423
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
Upvotes: 7
Views: 43296
Reputation: 13
we can do this using the entity framework var sum=dbcontext.table.select(a=>a.columnname).Sum();
Upvotes: 0
Reputation: 245389
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.
Upvotes: 25
Reputation: 15501
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.
Upvotes: -2