简体   繁体   中英

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

在此处输入图片说明

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 .

if OrderID is Type of int

replace

p.Field<long>("OrderID")

with

 p.Field<int>("OrderID")

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();

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