Harshal Yelpale
Harshal Yelpale

Reputation: 535

LINQ to List: Specified cast is not valid

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

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

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

Related Questions