The way C sorts the data in DataTable

  • 2020-05-24 06:01:18
  • OfStack

Just give me the example code


protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Age");// Because it's a string, it's not sorted correctly 
        dt.Rows.Add(" Xiao Ming ", "21");
        dt.Rows.Add(" Xiao zhang, ", "10");
        dt.Rows.Add(" The little red ", "9");
        dt.Rows.Add(" Small wei ", "7");
        dt.Rows.Add(" The little beauty ", "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  methods 1: Make up the age as 2 Bit, and then sort it, but it shouldn't be 0( For reference only )
        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  methods 2: Create a new DataTable That will be Age Type change to int type 
        DataTable dtNew = dt.Clone();
        dtNew.Columns["Age"].DataType = typeof(int);// The specified Age for Int type 
        foreach (DataRow s in dt.Rows)
        {
            dtNew.ImportRow(s);// Import old data 
        }

        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  methods 3: add 1 Columns, mainly for sorting 
        dt.Columns.Add("AgeLength", typeof(int), "len(Age)");// When you add the column, DataTable Column data is generated 

        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  methods 4: using LinQ, will DataTable Convert to a collection, and then call the collection's own sorting method to sort 
        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
    }


Related articles: