使用CopyToDataTable与&QUOT例外,新的{..}" LINQ查询 [英] Exception using CopyToDataTable with "new {..}" LINQ query
问题描述
从这个code我可以调用bmwCars.CopyToDataTable()如我所料。
VAR bmwCars =从车dataTable.AsEnumerable()
其中,car.Field<串GT(使)ToLower将()等于(宝马)。
选择车;
但是,当我改变code的一些语句下面,我不能叫CopyToDataTable(),为什么?
VAR bmwCars =从车dataTable.AsEnumerable()
其中,car.Field<串GT(使)ToLower将()等于(宝马)。
新选择
{
使= car.Field<串GT;(做),
颜色= car.Field<串GT;(颜色),
PetName = car.Field<串GT(PetName)
};
根据您的使用字段&LT的; T>
在的对象的dataTable
(这我假设的数据类型为车
)继承的DataRow
。这是需要调用 CopyToDataTable
扩展方法。由于写的,但是,你正在返回一个匿名类型的枚举不能继承的DataRow
。
所以,可能是你的
新选择
应
选择新车
让你返回一个的IEnumerable<汽车>
代替的IEnumerable<匿名类型
;&GT
根据您的车
类的确切结构,可能需要作一些小的变化syntatical。如果车
具有公共属性,制作
,颜色
,和 PetName
那么它会工作,我建议。相反,如果车
与方法签名构造近似等于
公共停车场(字符串作,串色,串petName)
那么你将不得不改变LINQ的语句为
VAR bmwCars =从车dataTable.AsEnumerable()
其中,car.Field<串GT(使)ToLower将()等于(宝马)。
选择新车(
car.Field<串GT;(做),
car.Field<串GT;(颜色),
car.Field<串GT(PetName)
);
From this code I can call bmwCars.CopyToDataTable() as I expected.
var bmwCars = from car in dataTable.AsEnumerable()
where car.Field<string>("Make").ToLower().Equals("bmw")
select car;
But when I have change some statement of code to below, I can't call CopyToDataTable(), why?
var bmwCars = from car in dataTable.AsEnumerable()
where car.Field<string>("Make").ToLower().Equals("bmw")
select new
{
Make = car.Field<string>("Make"),
Color = car.Field<string>("Color"),
PetName = car.Field<string>("PetName")
};
Based on your use of Field<T>
, the objects in dataTable
(which I am assuming are of type Car
) inherit DataRow
. This is necessary to call the CopyToDataTable
extension method. As written, however, you are returning an enumeration of an anonymous type which can not inherit DataRow
.
So, probably your
select new
should be
select new Car
so that you're returning an IEnumerable<Car>
instead of an IEnumerable<>
of anonymous type.
Depending on the exact structure of your Car
class, it might be necessary to make some minor syntatical changes. If Car
has public properties, Make
, Color
, and PetName
then it will work as I suggested. If, instead, Car
has a constructor with method signature approximately equal to
public Car(string make, string color, string petName)
then you will have to alter the LINQ statement to be
var bmwCars = from car in dataTable.AsEnumerable()
where car.Field<string>("Make").ToLower().Equals.("bmw")
select new Car(
car.Field<string>("Make"),
car.Field<string>("Color"),
car.Field<string>("PetName")
);
这篇关于使用CopyToDataTable与&QUOT例外,新的{..}&QUOT; LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!