Reputation: 4423
I've a DataTable orders
and I'm using lambda expression to filter out the records without any loops. The first line in the if condition works fine and returns me a valid record.
if (orders.Rows.Count > 0)
{
//This line returns a record
var defaultOrder = orders.Rows.Cast<DataRow>().Where(p => p.Field<bool>("IsDefault")).ToList();
//The line below gives me an exception Specified cast is not valid.
var defaultOrderID = orders.Rows.Cast<DataRow>().Where(p => p.Field<bool>("IsDefault")).Select(p => p.Field<long>("OrderID")).FirstOrDefault();
}
Now, I want to fetch value of a specific column from this record but I'm getting following exception
PS: I can see in DB and defaultOrder
variable in debug mode that value of OrderID
is 4.
Datatype of IsDefault
is bit and OrderID
is int in Database. Both are not null.
Upvotes: 0
Views: 957
Reputation: 566
You can check the data type of the field "OrderID" in DataRow, Rows will have no. of records under it, Expand any 1 record, Column properties, Select the field "OrderID" and check the data type of it.
If it is giving error for long and it has value 4 in DB than it should have a data type of Int32, use that one.
var defaultOrderID = orders.Rows.Cast<DataRow>().Where(p => p.Field<bool>("IsDefault")).Select(p => p.Field<Int32>("OrderID")).FirstOrDefault();
Upvotes: 1
Reputation: 45947
if OrderID
is Type of int
replace
p.Field<long>("OrderID")
with
p.Field<int>("OrderID")
Upvotes: 1