1 #region DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回 2 /// <summary> 3 /// DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回 4 /// eg:SortExprDataTable(dt,"Sex='男'","Time Desc",1) 5 /// </summary> 6 /// <param name="dt">传入的DataTable</param> 7 /// <param name="strExpr">筛选条件</param> 8 /// <param name="strSort">排序条件</param> 9 /// <param name="mode">1,直接用DefaultView按条件返回,效率较高;2,DataTable筛选,排序返回符合条件行组成的新DataTable</param> 10 public static DataTable SortDataTable(DataTable dt, string strExpr, string strSort, int mode) 11 { 12 switch (mode) 13 { 14 case 1: 15 //方法一 直接用DefaultView按条件返回 16 dt.DefaultView.RowFilter = strExpr; 17 dt.DefaultView.Sort = strSort; 18 return dt; 19 case 2: 20 //方法二 DataTable筛选,排序返回符合条件行组成的新DataTable 21 DataTable dt1 = new DataTable(); 22 DataRow[] GetRows = dt.Select(strExpr, strSort); 23 //复制DataTable dt结构不包含数据 24 dt1 = dt.Clone(); 25 foreach (DataRow row in GetRows) 26 { 27 dt1.Rows.Add(row.ItemArray); 28 } 29 return dt1; 30 default: 31 return dt; 32 } 33 } 34 #endregion 35 #region 获取DataTable前几条数据 36 /// <summary> 37 /// 获取DataTable前几条数据 38 /// </summary> 39 /// <param name="TopItem">前N条数据</param> 40 /// <param name="oDT">源DataTable</param> 41 /// <returns></returns> 42 public static DataTable DtSelectTop(int TopItem, DataTable oDT) 43 { 44 if (oDT.Rows.Count < TopItem) return oDT; 45 46 DataTable NewTable = oDT.Clone(); 47 DataRow[] rows = oDT.Select("1=1"); 48 for (int i = 0; i < TopItem; i++) 49 { 50 NewTable.ImportRow((DataRow)rows[i]); 51 } 52 return NewTable; 53 } 54 #endregion 55 56 #region 获取DataTable中指定列的数据 57 /// <summary> 58 /// 获取DataTable中指定列的数据 59 /// </summary> 60 /// <param name="dt">数据源</param> 61 /// <param name="tableName">新的DataTable的名词</param> 62 /// <param name="strColumns">指定的列名集合</param> 63 /// <returns>返回新的DataTable</returns> 64 public static DataTable GetTableColumn(DataTable dt, string tableName, params string[] strColumns) 65 { 66 DataTable dtn = new DataTable(); 67 if (dt == null) 68 { 69 throw new ArgumentNullException("参数dt不能为null"); 70 } 71 try 72 { 73 dtn = dt.DefaultView.ToTable(tableName, true, strColumns); 74 } 75 catch (Exception e) 76 { 77 throw new Exception(e.Message); 78 } 79 return dtn; 80 } 81 #endregion