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