c# - 将查询从 linq 复制到 Datatable 时出错

标签 c# linq ienumerable

我刚开始做一个需要 Linq to Sql 的项目,并且我已经能够进行查询和检索数据。但是现在我需要填写 DataTable使用我正在检索的数据。

我的第一个代码如下:

MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
            where cust.CustomerName != "Dante"
            orderby cust.CustomerName
            select new { Name = cust.CustomerName }; 

因此,因为我需要将查询内容复制到 Datatable我试过 this :

 IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

然后,我的代码如下所示:

IEnumerable<DataRow> myQuery = from cust in db.Customers.AsEnumerable()
                    where cust.Name != "Dante"
                    orderby cust.Name
                    select new { Name = cust.Name };

DataTable myDataTable = myQuery.CopyToDataTable<DataRow>();

但是对于这段代码,编译器会引发错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Data.DataRow>

错误出现在 select词。

那么,我做错了什么??我该怎么做才能避免这种转换问题?

希望有人能帮助我,在此先感谢。

最佳答案

有一种方法可以创建 DataTable来自 IEnumerable<DataRow> 以外的结果, 但它相当复杂。 Implement CopyToDataTable Where the Generic Type T Is Not a DataRow .

不过,对于您的情况,我建议您按以下方式进行。返回到您的原始查询:

MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
            where cust.CustomerName != "Dante"
            orderby cust.CustomerName
            select new { Name = cust.CustomerName };

然后定义你的单一字段DataTable因为当你最终创建一个 DataRow ,它需要一个模式来工作:

DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(
    new DataColumn()
    {
        DataType = System.Type.GetType("System.String"),
        ColumnName = "Name"
    }
);

最后,查看查询结果并手动添加 DataRows给你的DataTable .

foreach (var element in query)
{
    var row = myDataTable.NewRow();
    row["Name"] = element.Name;
    myDataTable.Rows.Add(row);
}

关于c# - 将查询从 linq 复制到 Datatable 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12289626/

相关文章:

c# - Socket tcp c# 如何清除输入缓冲区?

c# - 如何从 C# 中的 xml 中删除无效字符

c# - 使用 LINQ 构建递归层次结构

c# - 使用 EF 和 Linq 通过另一个表字段值查找表中的字段

.net - VB.NET 排序 IEnumerable 类

c# - 关于Registry CreateSubKey的简单问题

c# - LINQ to Entities 不支持“TimeOfDay” - 在 Linq 2 SQL 中查找总秒数

c# - 使用 "yield"时,为什么编译器生成的类型同时实现 IEnumerable 和 IEnumerator

c# - ASP.NET MVC POST 中的模型绑定(bind) IEnumerable?

c# - 包装一个 IEnumerable 并捕获异常