LINQ查询DataTable - 无法找到查询模式的实现

4

有人能告诉我为什么这段代码无法编译吗?错误信息如下:

未找到适用于源类型 System.Data.DataTable 的查询模式实现。没有找到 Where

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace caLINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Data Source=STEVEN-PC\\SQLEXPRESS;Initial Catalog=linqtest;Integrated Security=True;Pooling=False";
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                 connection.Open();
                 String cmdText = "select * from customers";
                 System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText, connection);
                 System.Data.SqlClient.SqlDataReader dr;
                 dr = cmd.ExecuteReader();
                 DataSet ds = new DataSet();
                 ds.Load(dr, LoadOption.OverwriteChanges, "tab1");
                 DataTable dt = ds.Tables[0];
                 var qy = from c in dt // error is here
                          where c.country == "Italy"
                          select c.name;
            }
            Console.ReadKey();
        }
    }
}

你应该考虑使用Linq2Sql,而不是填充数据表并查询它们。 - Magnus
2
你好,欢迎。您可以考虑在左侧勾选大的复选标记来标记其中一个答案作为已接受的答案。 - Gert Arnold
2个回答

12

尝试以下方法:

var qy = from c in dt.AsEnumerable()
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name");

AsEnumerable()会返回一个可以与LINQ一起使用的IEnumerable<DataRow>


1
感谢Magnus和KreepN。 在实现你们两位的建议后,它终于正常工作了。这是一个微不足道的应用程序,我只是想用它来尝试了解LINQ; 我想从填充DataTable并尝试查询它开始。现在我可以继续了。 SLB - user1480480
AsEnumerable() 很耗费资源。 - StackOrder
@StackOrder 不在 DataTable 上。 - Magnus

4

请调整你的代码(假设你的数据库列名为“国家”和“名称”):

var qy = from DataRow c in dt.Rows
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name");

或者
var qy = (from DataRow c in dt.Rows
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name")).ToList()

为了列出这些“名称”的清单。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接