using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;namespace WebApplication_study.Linq{ public partial class LinqStart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable dt = getDataTable.getData();//源数据 //Linq进行普通查询 var q1 = from dt1 in dt.AsEnumerable()//查询 orderby dt1.Field ("ID") descending//排序 where dt1.Field ("ID") > 2 && dt1.Field ("ID") < 6//条件 select dt1; Response.Write("查询结果为: "); foreach (var item in q1)//显示查询结果 { //Response.Write(" " + item.Field("Name"));//两种写法均可 Response.Write(" " + item["Name"]); } //查询结果用于新的DT DataTable newDT = q1.CopyToDataTable ();//经查询生成的DT可用于数据绑定 Response.Write(" 新的DT的结果为: "); foreach (var item2 in newDT.AsEnumerable())//显示查询结果 { Response.Write(" " + item2["Name"]); } // 修改查询的结果 Response.Write(" 修改查询结果前: "); var q3 = from dt3 in dt.AsEnumerable() select dt3; foreach (var item in q3) { Response.Write(" " + item["ID"] + " " + item["Name"] + " " + item["PID"] + " "); } Response.Write(" 修改查询结果后: "); foreach (var items in dt.AsEnumerable()) { int PID = (int)items["PID"]; items.SetField ("PID", PID + 100); } foreach (var item in q3) { Response.Write(" " + item["ID"] + " " + item["Name"] + " " + item["PID"] + " "); } //DataView测试 DataView dvDT = dt.AsDataView(); EnumerableRowCollection quert4 = from dv in dt.AsEnumerable() select dv; DataView dvDTQ = quert4.AsDataView(); //linq调用本地方法 //定义本地方法 Response.Write(" linq调用本地方法: "); int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var query = from i in num where check(i) select i; foreach (var item in query) { Response.Write(item + " "); } } /// /// 本地方法示例 /// /// ///public bool check(int num) { if (num > 5) return true; else return false; } }}
PS:如果出现指定转换无效的异常,说明查询语句里面有问题。一般是Field<T>的泛型有误,应当仔细检查DataTable中列的DataType。
然后还可可以这么写
IEnumerablequery = from order in orders.AsEnumerable() where order.Field ("OrderDate") > new DateTime(2001, 8, 1) select order;// Create a table from the query.DataTable boundTable = query.CopyToDataTable ();
本文转载自:http://www.cnblogs.com/sunxf2011/archive/2011/07/08/2101008.html