无法将类型为“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)