4

谁能告诉我为什么这不能编译?错误是:

找不到源类型的查询模式的实现System.Data.DataTableWhere未找到。

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();
        }
    }
}
4

2 回答 2

12

尝试:

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

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

于 2012-06-25T16:26:53.563 回答
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()

有关这些“名称”的列表。

于 2012-06-25T17:47:37.933 回答