LINQ操作创建强制转换异常

时间:2017-12-06 12:37:14

标签: excel linq c#-4.0 datatable

在从excel文件填充的数据表中读取数据时,获取“无法将类型'System.Double'的对象强制转换为'System.String'。”列数据类型为double时发生异常。我的代码如下所示

 var importedProducts = dtImportedData.AsEnumerable()
                        .Where(dtProduct => !string.IsNullOrWhiteSpace(dtProduct.Field<string>("product_id")))
                        .Select(dtProduct => new
                        {
                            product_id = dtProduct.Field<string>("product_id").Trim(),                              
                            product_qty = Convert.ToInt32(dtProduct.Field<double>("product_qty "))
                        }).ToList();

当product_id列具有text数据类型时,一切正常。但是当有双数据类型时,它会抛出异常。

我已经尝试过来自here

的解决方案

1 个答案:

答案 0 :(得分:3)

好吧,如果product_id是双精度而不是字符串,那么为什么要将其强制转换为string

.Where(row => !string.IsNullOrWhiteSpace(row.Field<double>("product_id").ToString()))
.Select(row => new
 {
    product_id = row.Field<double>("product_id"),                              
    product_qty = (int)row.Field<double>("product_qty")
 })

我不喜欢使用包含!string.IsNullOrWhiteSpacedouble字段的double?方法。我很确定你可以使用(待测试):

.Where(row => row.Field<double?>("product_id").HasValue)
.Select(row => new
 {
   product_id = row.Field<double?>("product_id").Value,                              
   product_qty = (int)row.Field<double>("product_qty")
 })

如果您不知道DataColumnDataTable的类型,可以在调试器中执行此操作:

dtImportedData.Columns["product_id"].DataType;

这是您必须在Field<T>中使用的内容。

如果类型真的改变为注释,那么这是最安全的:

.Where(row => !string.IsNullOrWhiteSpace(row["product_id"].ToString()))
.Select(row => new
 {
    product_id = row["product_id"].ToString().Trim(),                              
    product_qty = int.Parse(row["product_qty"].ToString().Trim())
 })