SRJ
SRJ

Reputation: 198

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?

Upvotes: 3

Views: 4092

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

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")); 

Upvotes: 3

Related Questions