简体   繁体   中英

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 :).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM