简体   繁体   中英

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

I wrote this code to find which one of dtExistCosts doesn,y exit in costsList.

var costMustbeDeleteDt = (
        from e in dtExistCosts.AsEnumerable()
        where !(from c in costsList 
                select Convert.ToString(c.CostRecordId))
                            .Contains(e.Field<string>("DETAIL_HAZ_PK"))
        select e).CopyToDataTable();

but when I run it I get the error:

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

in

!(from c in costsList 
  select Convert.ToString(c.CostRecordId))
        .Contains(e.Field<string>("DETAIL_HAZ_PK"))

why?

.Contains(e.Field<string>("DETAIL_HAZ_PK"))

The exception should be at this line, you cannot do explicit conversion for a decimal to string as the exception suggested.

You may do:

.Contains(Convert.ToString(e.Field<decimal>("DETAIL_HAZ_PK")))

Of course, compare values directly by decimal should be the case but this answer your question on why.

It looks like you are trying to convert two numerical values (c.CostRecordId and the value of "DETAIL_HAZ_PK") to string before comparing them which is not only unnecessary but also leads to the error you described.

Try this instead:

var costMustbeDeleteDt = (from e in dtExistCosts.AsEnumerable()
  where !(from c in costsList select c.CostRecordId)
      .Contains(e.Field<decimal>("DETAIL_HAZ_PK"))
  select e).CopyToDataTable();

Additionally, I would suggest to improve the readability of your selection by introducing a variable for the costList IDs and converting your LINQ queries to the method chain syntax:

var costsListIds = costsList.Select (c => c.CostRecordId);

var costMustbeDeleteDt = dtExistCosts
    .Where (existCost => !costsListIds.Contains (existCost.Field<decimal>("DETAIL_HAZ_PK"))
    .CopyToDataTable();

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