使用带有“new {..}"的 CopyToDataTable 的异常;LINQ 查询 [英] Exception using CopyToDataTable with "new {..}" LINQ query

查看:41
本文介绍了使用带有“new {..}"的 CopyToDataTable 的异常;LINQ 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此代码中,我可以按预期调用 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")
                          };

推荐答案

根据您对 Field 的使用,dataTable 中的对象(我假设属于 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 而不是匿名类型的 IEnumerable<>.

so that you're returning an IEnumerable<Car> instead of an IEnumerable<> of anonymous type.

根据您的 Car 类的确切结构,可能需要进行一些细微的语法更改.如果 Car 有公共属性,MakeColorPetName 那么它会按照我的建议工作.相反,如果 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆