对 datatable 排序及分页
在一个项目中需要对查询的结果 datatable 倒序输出,第一个想到的是对 datatable 排序一次,然后按正常输出:
1 private DataTable SortDesc(DataTable dt){
2 DataView dv = new DataView();
3 dv.Table = dt;
4 dv.Sort = "autoid desc";
5 return dv.ToTable;
6 }
2 DataView dv = new DataView();
3 dv.Table = dt;
4 dv.Sort = "autoid desc";
5 return dv.ToTable;
6 }
另外一个方法是 for 循环 倒序输出:
for(int i= dt.rows.count-1;i>=0;i--){
//do something
}
//do something
}
对应 DataTable 分页:
/// <summary>
/// 根据索引和pagesize返回记录
/// </summary>
/// <param name="dt">记录集 DataTable</param>
/// <param name="PageIndex">当前页</param>
/// <param name="pagesize">一页的记录数</param>
/// <returns></returns>
public static DataTable SplitDataTable(DataTable dt, int PageIndex, int PageSize)
{
if (PageIndex == 0)
return dt;
DataTable newdt = dt.Clone();
//newdt.Clear();
int rowbegin = (PageIndex - 1) * PageSize;
int rowend = PageIndex * PageSize;
if (rowbegin >= dt.Rows.Count)
return newdt;
if (rowend > dt.Rows.Count)
rowend = dt.Rows.Count;
for (int i = rowbegin; i <= rowend - 1; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
}
return newdt;
}
/// 根据索引和pagesize返回记录
/// </summary>
/// <param name="dt">记录集 DataTable</param>
/// <param name="PageIndex">当前页</param>
/// <param name="pagesize">一页的记录数</param>
/// <returns></returns>
public static DataTable SplitDataTable(DataTable dt, int PageIndex, int PageSize)
{
if (PageIndex == 0)
return dt;
DataTable newdt = dt.Clone();
//newdt.Clear();
int rowbegin = (PageIndex - 1) * PageSize;
int rowend = PageIndex * PageSize;
if (rowbegin >= dt.Rows.Count)
return newdt;
if (rowend > dt.Rows.Count)
rowend = dt.Rows.Count;
for (int i = rowbegin; i <= rowend - 1; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
}
return newdt;
}