using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ty.net.test.Sort { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } DataTable test() { DataTable dtA = new DataTable(); dtA.Columns.Add("id", typeof(int)); dtA.Columns.Add("goodNum", typeof(double)); dtA.Columns.Add("generalNum", typeof(double)); dtA.Columns.Add("badNum", typeof(double)); //dtA.Rows.Add(1, "20", "30", "50"); //dtA.Rows.Add(2, "90", "3", "2"); dtA.Rows.Add(3, "11", "5", "10"); dtA.Rows.Add(4, "10", "32", "-2"); dtA.Rows.Add(5, "66", "55", "44"); return dtA; } protected void Button1_Click(object sender, EventArgs e) { //升序 DataTable dt = LinqSortDataTable2(test(), "badNum"); GridView1.DataSource = dt; GridView1.DataBind(); } protected void Button2_Click(object sender, EventArgs e) { //降序 DataTable dt = LinqSortDataTable(test(), 3); GridView1.DataSource = dt; GridView1.DataBind(); } /// <summary> /// 对datatable按照某一列进行linq排序,因为dataview自带的排序处理不了负数的排序 /// </summary> /// <param name="tmpDt">需要排序的datatable</param> /// <param name="sortId">排序的列序号,从0开始</param> /// <returns></returns> protected DataTable LinqSortDataTable(DataTable tmpDt, int sortId) { DataView dv = tmpDt.DefaultView; var query = (from item in tmpDt.AsEnumerable() orderby Convert.ToInt32(item[sortId]) descending select item); //重新排序 dv = query.AsDataView(); return dv.ToTable(); } /// <summary> /// 对datatable按照某一列进行linq排序 /// </summary> /// <param name="tmpDt">需要排序的datatable</param> /// <param name="sortId">排序的列序号,从0开始</param> /// <returns></returns> protected DataTable LinqSortDataTable2(DataTable tmpDt, string columnName) { DataView dv = tmpDt.DefaultView; var query = (from item in tmpDt.AsEnumerable() orderby item[columnName] select item); //重新排序 dv = query.AsDataView(); return dv.ToTable(); } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ty.net.test.Sort.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="升序" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="降序" OnClick="Button2_Click" /> <asp:GridView ID="GridView1" runat="server"></asp:GridView> </div> </form> </body> </html>
可能你遇到这个问题, AsEnumerable方法找不到?
添加引用了System.Data.DataSetExtensions 搞定!!!!