Exception using CopyToDataTable with “new {..}” LINQ query

后端 未结 3 1718
孤街浪徒
孤街浪徒 2020-11-27 23:27

From this code I can call bmwCars.CopyToDataTable() as I expected.

var bmwCars = from car in dataTable.AsEnumerable()
                          where car.Fie         


        
3条回答
  •  眼角桃花
    2020-11-28 00:13

    Based on your use of Field, 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 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("Make").ToLower().Equals.("bmw")
                  select new Car(
                      car.Field("Make"),
                      car.Field("Color"),
                      car.Field("PetName")                          
                  );
    

提交回复
热议问题