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)