Lord-David
Lord-David

Reputation: 545

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.

Upvotes: 0

Views: 3429

Answers (4)

Darth Scitus
Darth Scitus

Reputation: 568

I know this is old but I wanted to drop my answer here for anyone else. I was trying to create a POCO class for a stored procedure and I was using floats instead of doubles for some of the returned values. Just make sure your types are correct.

Upvotes: -1

Mohamed Awadallah
Mohamed Awadallah

Reputation: 41

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.

Upvotes: 0

user6002047
user6002047

Reputation:

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)

Upvotes: 2

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131334

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)

Upvotes: 2

Related Questions