谁能告诉我为什么这不编译?错误是:
无法找到源类型
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();
}
}
}
答案 0 :(得分:9)
尝试:
var qy = from c in dt.AsEnumerable()
where c.Field<string>("country") == "Italy"
select c.Field<string>("name");
AsEnumerable()
将返回可与LINQ一起使用的IEnumerable<DataRow>
。
答案 1 :(得分:3)
将代码调整为(我假设您的数据库列是“country”和“name”:
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()
列出这些“名字”。