tags:

views:

482

answers:

2

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")
                          };
+1  A: 

Because you're returning a new anonymous type, not the car object itself.

MiffTheFox
+1  A: 

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")                          
              );
Jason