M.S.
M.S.

Reputation: 4423

Specified cast is not valid in lambda expression of DataRow List while fetching a column value

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

enter image description here

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

Answers (2)

sumngh
sumngh

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

fubo
fubo

Reputation: 45947

if OrderID is Type of int

replace

p.Field<long>("OrderID")

with

 p.Field<int>("OrderID")

Upvotes: 1

Related Questions