默認情況下,即便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
