I have the following code:
var query =
from product in products.AsEnumerable()
where product.Field<string>("Product") == "Phone"
select new
{
Name = product.Field<string>("Name"),
ProductNumber = product.Field<string>("ProductNumber"),
ListPrice = product.Field<Decimal>("Price")
};
But I am getting the following error:
Unable to cast object of type 'System.Int32' to type 'System.String'.
I assume that's because in the ProductNumber
column I don't always have doesn't always have strings, and in the first row the ProductNumber
is actually an int
. I've tried converting and casting them to string, but didn't work.
How can I fix this?
From the documentation of Field<T>
:
InvalidCastException
[is thrown when] the value type of the underlying column could not be cast to the type specified by the generic parameter, T.
It looks like in your case the column type is a nullable integer, so you need to do something like this:
var query =
from product in products.AsEnumerable()
where product.Field<string>("Product") == "Phone"
select new
{
Name = product.Field<string>("Name"),
// Below, I am using ""+... idiom for a null-safe ToString
ProductNumber = ""+product.Field<int?>("ProductNumber"),
ListPrice = product.Field<Decimal>("Price")
};
The idea is to retrieve the value as an int
, but accept data rows where the data is missing.
If you do not mind ProductNumber
of your anonymous class being nullable int
s instead of string
s, remove the ""+
part of the expression.
首先,使用ProductNumber作为字符串获取可枚举的记录,然后在Enumerable上进行从字符串到整数的转换。
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.