无法将类型为“System.Double”的对象转换为键入“System.String”的linq查询 [英] Unable to cast object of type 'System.Double' to type 'System.String' linq query

查看:816
本文介绍了无法将类型为“System.Double”的对象转换为键入“System.String”的linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Linq的新手,下面的行给了我无法输入System.Double类型的对象来键入System.String。如何解决它?

I'm new to Linq, the below line gives me "Unable to cast object of type 'System.Double' to type 'System.String'". How can I resolve it?

dt.AsEnumerable().Where(dataRow => !string.IsNullOrEmpty(dataRow.Field<string>(dc.ColumnName).First().ToString()) && (dataRow.Field<int>(dc.ColumnName) == 1)).Count() > 3

我正在查询DataTable列。

I'm querying a DataTable column.

推荐答案

我怀疑在尝试过滤等于1的行时遇到NullReferenceException。为了避免这种情况,请返回一个可空的类型,其中 Field< double? >(),例如:

I suspect you encountered a NullReferenceException while trying to filter for rows that are equal to 1. To avoid this, return a nullable type with Field<double?>(), eg:

dt.AsEnumerable()
  .Where(dataRow => dataRow.Field<double?>(dc.ColumnName) == 3m))
  .Count() > 3

如果该字段为空,比较将失败。

The comparison will fail if the field is null.

如果要在将NULL转换为例如0时检索列的值,可以使用 ?? 运算符:

If you want to retrieve the column's value while converting the NULL to eg 0, you can use the ?? operator:

.Select( dataRow => dataRow.Field<double?>(dc.ColumnName) ?? 0m)

这篇关于无法将类型为“System.Double”的对象转换为键入“System.String”的linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆