轉自:http://www.cnblogs.com/linyechengwei/archive/2010/06/14/1758337.html
http://blog.csdn.net/smartsmile2012/article/details/7900464
在C#中要對Datatable排序,可使用DefaultView的Sort方法。先獲取Datatable的DefaultView,然后設置得到的Dataview的sort屬性,最后用視圖的ToTable方法將排好序的dataview導出為Datatable。
代碼如下:
一、 Datatable排序
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 12, "lwolf" });
dt.Rows.Add(new object[] { 100,"kkkkk"});
dt.Rows.Add(new object[] { 19,"jim" });
dt.Rows.Add(new object[] { 1,"test" });
DataTable dtCopy = dt.Copy();
DataView dv = dt.DefaultView;
dv.Sort = "ID";
dtCopy = dv.ToTable();
二、獲取DataTable前幾條數據
#region 獲取DataTable前幾條數據
/// <summary>
/// 獲取DataTable前幾條數據
/// </summary>
/// <param name="TopItem">前N條數據</param>
/// <param name="oDT">源DataTable</param>
/// <returns></returns>
public static DataTable DtSelectTop(int TopItem, DataTable oDT)
{
if (oDT.Rows.Count < TopItem) return oDT;
DataTable NewTable = oDT.Clone();
DataRow[] rows = oDT.Select("1=1");
for (int i = 0; i < TopItem; i++)
{
NewTable.ImportRow((DataRow)rows[i]);
}
return NewTable;
}
#endregion
