zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#对DataTable里数据排序的方法

2023-06-13 09:15:12 时间

直接给个实例代码吧

复制代码代码如下:

protectedvoidPage_Load(objectsender,EventArgse)
    {
        DataTabledt=newDataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");//因为是字符串,所以排序不对
        dt.Rows.Add("小明","21");
        dt.Rows.Add("小张","10");
        dt.Rows.Add("小红","9");
        dt.Rows.Add("小伟","7");
        dt.Rows.Add("小美","3");
        dt.DefaultView.Sort="AgeASC";
        dt=dt.DefaultView.ToTable();

        foreach(DataRowsindt.Rows)
        {
            Response.Write(s["Age"].ToString()+"--"+s["Name"].ToString()+"<br/>");
        }
        Response.Write("------------------1----------------<br/>");

 
        #region方法1:将年龄补齐为2位,然后再进行排序,但是实际不应该有0(仅作参考)
        for(inti=0;i<dt.Rows.Count;i++)
        {
            dt.Rows[i]["Age"]=dt.Rows[i]["Age"].ToString().PadLeft(2,"0");
        }
        dt.DefaultView.Sort="AgeASC";

        dt=dt.DefaultView.ToTable();

        foreach(DataRowsindt.Rows)
        {
            Response.Write(s["Age"].ToString()+"--"+s["Name"].ToString()+"<br/>");
        }
        #endregion

        Response.Write("------------------2----------------<br/>");

        #region方法2:创建新的DataTable,将Age类型变更为int类型
        DataTabledtNew=dt.Clone();
        dtNew.Columns["Age"].DataType=typeof(int);//指定Age为Int类型
        foreach(DataRowsindt.Rows)
        {
            dtNew.ImportRow(s);//导入旧数据
        }

        dtNew.DefaultView.Sort="AgeASC";
        dtNew=dtNew.DefaultView.ToTable();

        foreach(DataRowsindtNew.Rows)
        {
            Response.Write(s["Age"].ToString()+"--"+s["Name"].ToString()+"<br/>");
        }
        #endregion

        Response.Write("-----------------3-----------------<br/>");

        #region方法3:添加一列,主要用于排序
        dt.Columns.Add("AgeLength",typeof(int),"len(Age)");//添加该列时,DataTable列数据即生成

        dt.DefaultView.Sort="AgeLength,AgeASC";
        dt=dt.DefaultView.ToTable();

        foreach(DataRowsindt.Rows)
        {
            Response.Write(s["Age"].ToString()+"--"+s["Name"].ToString()+"<br/>");
        }
        #endregion

        Response.Write("-----------------4-----------------<br/>");

        #region方法4:运用LinQ,将DataTable转换为集合,再调用集合自带的排序方法进行排序
        foreach(DataRowsindt.Rows.Cast<DataRow>().OrderBy(r=>int.Parse(r["Age"].ToString())))
        {
            Response.Write(s["Age"].ToString()+"--"+s["Name"].ToString()+"<br/>");
        }
        #endregion
    }