[英]linq select field type unknown
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'.
无法将类型为“ System.Int32”的对象转换为类型为“ 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
. 我认为这是因为在
ProductNumber
列中我并不总是拥有字符串,并且在第一行中ProductNumber
实际上是一个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>
: 从
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.InvalidCastException
[在以下情况时引发]基础列的值类型无法转换为通用参数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. 想法是将值作为
int
检索,但接受缺少数据的数据行。
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
您的匿名类是可空的int
!而非string
S,取出""+
表达式的一部分。
首先,使用ProductNumber作为字符串获取可枚举的记录,然后在Enumerable上进行从字符串到整数的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.