Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do sum of a column with LINQ?

  var GrandTotal = dt.AsEnumerable().Sum(cols => Convert.ToDecimal(cols.Field<string>("TotalPrice"))); 

is Giving Error:

Unable to cast object of type 'System.Decimal' to type 'System.String'

How can I Correct it?

like image 464
SRJ Avatar asked Jan 20 '26 06:01

SRJ


1 Answers

Your TotalPrice column contains decimal values, but you are trying to cast row field value to string. Cast to decimal directly instead:

var GrandTotal = dt.AsEnumerable()
                   .Sum(r => r.Field<decimal>("TotalPrice")); 
like image 163
Sergey Berezovskiy Avatar answered Jan 22 '26 19:01

Sergey Berezovskiy