【转】C# Datatable排序与取前几行数据

时间:2022-09-23 08:13:40

转自: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