|
- protected void Page_Load(object sender, EventArgs e)
- {
- DataTable dt = new DataTable();
- 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 = "Age ASC";
- dt = dt.DefaultView.ToTable();
- foreach (DataRow s in dt.Rows)
- {
- Response.Write(s["Age"].ToString() + "--" + s["Name"].ToString() + "<br/>");
- }
- Response.Write("------------------1----------------<br/>");
-
- #region 方法1:将年龄补齐为2位,然后再进行排序,但是实际不应该有0(仅作参考)
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- dt.Rows[i]["Age"] = dt.Rows[i]["Age"].ToString().PadLeft(2, '0');
- }
- dt.DefaultView.Sort = "Age ASC";
- dt = dt.DefaultView.ToTable();
- foreach (DataRow s in dt.Rows)
- {
- Response.Write(s["Age"].ToString() + "--" + s["Name"].ToString() + "<br/>");
- }
- #endregion
- Response.Write("------------------2----------------<br/>");
- #region 方法2:创建新的DataTable,将Age类型变更为int类型
- DataTable dtNew = dt.Clone();
- dtNew.Columns["Age"].DataType = typeof(int);//指定Age为Int类型
- foreach (DataRow s in dt.Rows)
- {
- dtNew.ImportRow(s);//导入旧数据
- }
- dtNew.DefaultView.Sort = "Age ASC";
- dtNew = dtNew.DefaultView.ToTable();
- foreach (DataRow s in dtNew.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,Age ASC";
- dt = dt.DefaultView.ToTable();
- foreach (DataRow s in dt.Rows)
- {
- Response.Write(s["Age"].ToString() + "--" + s["Name"].ToString() + "<br/>");
- }
- #endregion
- Response.Write("-----------------4-----------------<br/>");
- #region 方法4:运用LinQ,将DataTable转换为集合,再调用集合自带的排序方法进行排序
- foreach (DataRow s in dt.Rows.Cast<DataRow>().OrderBy(r => int.Parse(r["Age"].ToString())))
- {
- Response.Write(s["Age"].ToString() + "--" + s["Name"].ToString() + "<br/>");
- }
- #endregion
- }
复制代码
|
|