简体   繁体   中英

Unable to cast object of type 'System.Double' to type 'System.String' linq query

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

I'm querying a DataTable column.

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.

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)

The row which you are trying to cast as a string is having data type as double. Instead of dataRow.Field<string>(dc.ColumnName) , it should be dataRow.Field<double>(dc.ColumnName)

First you can refer to this Answer , but i will try to simplify this problem.

If the value of the specified DataColumn is null and T is a reference type or nullable type, the return type will be null. The Field method will not return Value.

DataRowExtensions.Field<T> Method (DataRow, String)

it appeared in .NET 3.5 and it provides strongly-Typed access to every column in rows, and also support types.

so you can use Convert.ToDouble(row["dc.ColumnName"]) to avoid the nullable value returns.

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