Linq如何查询弱类型的Datatable

可以通过调用DataTable的扩展方法AsEnumerable方法,返回IEnumerable<T>对象,便于LINQ查询。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var products = from product in GetDataTable().AsEnumerable()
select new { ProductID = product.Field<int>("产品ID"), ProductName = product.Field<string>("产品名称")};
this.GridView1.DataSource = products;
this.GridView1.DataBind();
}

private DataTable GetDataTable()
{
DataTable table = new DataTable();
using (OleDbConnection conn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + Server.MapPath("~/App_Data/Northwind.mdb")))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = "SELECT * FROM Products";
comm.CommandType = CommandType.Text;
conn.Open();
table.Load(comm.ExecuteReader(CommandBehavior.CloseConnection));
}
}
return table;
}
}

Field<int>("产品ID")功能相当于传统的DataRow["产品ID"],差别是Field语法针对特定的字段值,提供了强类型的支持。指定<T>类型,该类型必须与数据库的Schema定义相对应。