DataTable排序結果的糾正

來源:互聯網
上載者:User

預設情況下,即便db中某一列的值是數字,查詢出來的DataSet/DataTable裡,Column的類型都是String型,所以當用dataTable.DefaultView.Sort ="XXX ASC"排序時,都是按字串排序處理的,並不是我們想要的結果,下面給出了二種解決辦法:

using System;using System.Data;namespace DataTableSortSample{    class Program    {        static void Main(string[] args)        {            DataTable dt = new DataTable();            dt.Columns.Add("Month");            dt.Rows.Add("1");            dt.Rows.Add("11");            dt.Rows.Add("2");            dt.Rows.Add("12");            dt.DefaultView.Sort = "Month ASC";            dt = dt.DefaultView.ToTable();            foreach (DataRow s in dt.Rows)            {                Console.WriteLine(s["Month"]);            }            Console.WriteLine("----------------------------------");            #region 方法1:將月份補齊為2位 (前提:補齊這種方案並非所有需求都能接受,這個要看該列的業務含義)            for (int i = 0; i < dt.Rows.Count; i++)            {                dt.Rows[i]["Month"] = dt.Rows[i]["Month"].ToString().PadLeft(2, '0');            }            dt.DefaultView.Sort = "Month ASC";            dt = dt.DefaultView.ToTable();            foreach (DataRow s in dt.Rows)            {                Console.WriteLine(s["Month"]);            }            #endregion            Console.WriteLine("----------------------------------");            #region 方法2:建一個新DataTable,將Month列類型,修改成int型,然後匯入資料            DataTable dtNew = dt.Clone();            dtNew.Columns["Month"].DataType = typeof (int);//重新指定列類型為int型            foreach (DataRow s in dt.Rows)            {                dtNew.ImportRow(s);//匯入舊資料            }            dtNew.DefaultView.Sort = "Month ASC";            dtNew = dtNew.DefaultView.ToTable();            foreach (DataRow s in dtNew.Rows)            {                Console.WriteLine(s["Month"]);            }            #endregion            Console.Read();        }    }}

  運行結果:

1
11
12
2
----------------------------------
01
02
11
12
----------------------------------
1
2
11
12

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.