对datatable操作,查询

#region DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回  
/// <summary>  
/// DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回  
/// eg:SortExprDataTable(dt,"Sex='男'","Time Desc",1)  
/// </summary>  
/// <param name="dt">传入的DataTable</param>  
/// <param name="strExpr">筛选条件</param>  
/// <param name="strSort">排序条件</param>  
/// <param name="mode">1,直接用DefaultView按条件返回,效率较高;2,DataTable筛选,排序返回符合条件行组成的新DataTable</param>  
public static DataTable SortDataTable(DataTable dt, string strExpr, string strSort, int mode)  
{  
    switch (mode)  
    {  
        case 1:  
            //方法一 直接用DefaultView按条件返回  
            dt.DefaultView.RowFilter = strExpr;  
            dt.DefaultView.Sort = strSort;  
            return dt;  
        case 2:  
            //方法二 DataTable筛选,排序返回符合条件行组成的新DataTable  
            DataTable dt1 = new DataTable();  
            DataRow[] GetRows = dt.Select(strExpr, strSort);  
            //复制DataTable dt结构不包含数据  
            dt1 = dt.Clone();  
            foreach (DataRow row in GetRows)  
            {  
                dt1.Rows.Add(row.ItemArray);  
            }  
            return dt1;  
        default:  
            return dt;  
    }  
}  
#endregion  



harp] view plaincopyprint?
#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  
 
#region 获取DataTable中指定列的数据  
/// <summary>  
/// 获取DataTable中指定列的数据  
/// </summary>  
/// <param name="dt">数据源</param>  
/// <param name="tableName">新的DataTable的名词</param>  
/// <param name="strColumns">指定的列名集合</param>  
/// <returns>返回新的DataTable</returns>  
public static DataTable GetTableColumn(DataTable dt, string tableName, params string[] strColumns)  
{  
    DataTable dtn = new DataTable();  
    if (dt == null)  
    {  
        throw new ArgumentNullException("参数dt不能为null");  
    }  
    try  
    {  
        dtn = dt.DefaultView.ToTable(tableName, true, strColumns);  
    }  
    catch (Exception e)  
    {  
        throw new Exception(e.Message);  
    }  
    return dtn;  
}  
#endregion  

  

posted @ 2014-04-08 19:35  mile  阅读(9428)  评论(0编辑  收藏  举报