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<int>("ID") descending//排序 where dt1.Field<int>("ID") > 2 && dt1.Field<int>("ID") < 6//条件 select dt1; Response.Write("查询结果为:<br/>"); foreach (var item in q1)//显示查询结果 { //Response.Write("<br/>" + item.Field<string>("Name"));//两种写法均可 Response.Write("<br/>" + item["Name"]); } //查询结果用于新的DT DataTable newDT = q1.CopyToDataTable<DataRow>();//经查询生成的DT可用于数据绑定 Response.Write("<br/><br/>新的DT的结果为:<br/>"); foreach (var item2 in newDT.AsEnumerable())//显示查询结果 { Response.Write("<br/>" + item2["Name"]); } // 修改查询的结果 Response.Write("<br/>修改查询结果前:<br/>"); var q3 = from dt3 in dt.AsEnumerable() select dt3; foreach (var item in q3) { Response.Write("<br/>" + item["ID"] + " " + item["Name"] + " " + item["PID"] + " "); } Response.Write("<br/>修改查询结果后:<br/>"); foreach (var items in dt.AsEnumerable()) { int PID = (int)items["PID"]; items.SetField<int>("PID", PID + 100); } foreach (var item in q3) { Response.Write("<br/>" + item["ID"] + " " + item["Name"] + " " + item["PID"] + " "); } //DataView测试 DataView dvDT = dt.AsDataView(); EnumerableRowCollection<DataRow> quert4 = from dv in dt.AsEnumerable() select dv; DataView dvDTQ = quert4.AsDataView(); //linq调用本地方法 //定义本地方法 Response.Write("<br/>linq调用本地方法:<br/>"); 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 + " "); } } /// <summary> /// 本地方法示例 /// </summary> /// <param name="num"></param> /// <returns></returns> public bool check(int num) { if (num > 5) return true; else return false; } } }
PS:如果出现指定转换无效的异常,说明查询语句里面有问题。一般是Field<T>的泛型有误,应当仔细检查DataTable中列的DataType。
然后还可可以这么写
IEnumerable<DataRow> query = from order in orders.AsEnumerable() where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1) select order; // Create a table from the query. DataTable boundTable = query.CopyToDataTable<DataRow>();
本文转载自:http://www.cnblogs.com/sunxf2011/archive/2011/07/08/2101008.html