【问题标题】:Unable to cast object of type 'System.Decimal' to type 'System.String'无法将“System.Decimal”类型的对象转换为“System.String”类型
【发布时间】:2015-03-09 16:36:29
【问题描述】:

我编写这段代码是为了找出 dtExistCosts 中的哪一个没有退出 costList。

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

但是当我运行它时,我得到了错误:

无法将 System.Decimal 类型的对象转换为 System.String 类型

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

为什么?

【问题讨论】:

  • DETAIL_HAZ_PK是什么类型?
  • 这是我要检查的列的名称。
  • 太好了,它是什么type

标签: c# linq


【解决方案1】:
.Contains(e.Field<string>("DETAIL_HAZ_PK"))

异常应该在这一行,你不能像异常建议的那样将小数显式转换为字符串。

你可以这样做:

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

当然,应该是直接按小数比较值,但这回答了你的问题。

【讨论】:

    【解决方案2】:

    您似乎正在尝试将两个数值(c.CostRecordId 和“DETAIL_HAZ_PK”的值)转换为字符串,然后再进行比较,这不仅没有必要,而且还会导致您描述的错误。

    试试这个:

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

    此外,我建议通过为 costList ID 引入变量并将 LINQ 查询转换为方法链语法来提高选择的可读性:

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

    【讨论】:

    • 谢谢。我做到了,我也将 c.CostRecordId 转换为十进制,并且它有效。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2012-09-07
    • 2014-03-14
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多