带有“new {..}”的CopyToDataTable的异常LINQ查询 [英] Exception using CopyToDataTable with "new {..}" LINQ query
问题描述
从这个代码我可以按照我的预期调用bmwCars.CopyToDataTable()。
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;
但是,当我将一些代码更改到下面时,我不能调用CopyToDataTable()为什么?
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")
};
推荐答案
根据您使用的字段< T>
, dataTable
中的对象(我假设的类型为$ code> Car )继承 DataRow
。调用 CopyToDataTable
扩展方法。然而,正如你所写的那样,你返回一个匿名类型的枚举,它不能继承 DataRow
。
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
.
所以,可能您的
select new
应该是
select new Car
,以便您返回一个 IEnumerable< Car>
而不是 IEnumerable< < / code>的匿名类型。
so that you're returning an IEnumerable<Car>
instead of an IEnumerable<>
of anonymous type.
根据您的 Car
类的确切结构,可能需要进行一些小的合成变更。如果 Car
具有公共属性, Make
, Color
,以及 PetName
然后它将按照我的建议工作。如果相反, Car
具有方法签名大约等于
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)
那么你将不得不更改LINQ声明为
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")
);
这篇关于带有“new {..}”的CopyToDataTable的异常LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!