Reputation: 535
I'm trying to calculate the sum of a column where my condition match. The records that have in the list(lstSumQty) for column "Quantity" is in string format (Note: As this data is coming from excel file which is upload by the end user. So, Quantity column sometimes in a string or in decimal).
Due to column string DataType, the system throws an exception: Specified cast is not valid, How to cast it or resolve?
Data in list
Unit Quantity
"t" "10"
"t" "05"
"kg" "14"
"t" "02"
The result should be: tUnitTotal = 17
See the below piece of code
tUnitTotal = lstSumQty
.AsEnumerable()
.Where(row => row.Field<string>("Unit") == "t")
.Sum(row => row.Field<decimal>("Quantity"))
.ToString();
Instead of List, I'm also ok with DataSet or DataTable using LINQ.
Any help would be appreciated :).
Upvotes: 1
Views: 675
Reputation: 37000
The generic type-argument (<decimal>
in your case) does not indicate what you want it to return, but what it is in the database.
So you need to convert your strings to numbers before calculating their sum:
tUnitTotal = lstSumQty.AsEnumerable()
.Where(row => row.Field<string>("Unit") == "t")
.Sum(row => Convert.ToDecimal(row.Field<string>("Quantity")))
.ToString();
Upvotes: 7