C# CopyToDataTable不工作…生成错误

C# CopyToDataTable不工作…生成错误,c#,linq,C#,Linq,我从msdn获得了一个示例,代码是: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LINQTest { public partial class

我从msdn获得了一个示例,代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LINQTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Item[] items = new Item[] 
            { new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"}, 
              new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
              new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
              new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

                        // Load into an existing DataTable, expand the schema and
                        // autogenerate a new Id.
                        DataTable table = new DataTable();
                        DataColumn dc = table.Columns.Add("NewId", typeof(int));
                        dc.AutoIncrement = true;
                        table.Columns.Add("ExtraColumn", typeof(string));

                        var query = from i in items
                                    where i.Price > 9.99
                                    orderby i.Price
                                    select new { i.Price, i.Genre };

                       query.CopyToDataTable(table, LoadOption.PreserveChanges);

                    }
    }

    public class Item
    {
        public int Id { get; set; }
        public double Price { get; set; }
        public string Genre { get; set; }
    }

    public class Book : Item
    {
        public string Author { get; set; }
    }

    public class Movie : Item
    {
        public string Director { get; set; }
    }
}

CopyToDataTable出现错误。我遗漏了什么吗?

您必须将对象强制转换为数据行

试试这个:

    query.Select(el =>
                     {
                         DataRow row =
                             table.NewRow();
                         row["ExtraColumn"] = el.Genre;
                         return row;
                     }
        ).CopyToDataTable(table, LoadOption.PreserveChanges);

你遇到了什么类型的错误?你问了263个问题,但你仍然发布了一个只有一堵墙的代码b没有正确的格式c没有错误详细信息?我自己尝试过,因为我可以学到一些东西。但是给我们你所犯的错误会让事情变得容易很多。