一 復制DataTable中符合條件的DataRow到新的DataTable中
One:
DataTable TableTemp = new DataTable();//臨時table
DataTable tableAd = new Web.DAL.FreeBase().TranSQLGetTable("select a.ClassName,b.ParentId,b.Name,b.Pic,b.Url,b.Sorts from AdClass a inner join Ad b on a.Id=b.ParentId");//查詢的結果 if (tableAd != null && tableAd.Rows.Count > 0) { Tableflag = tableAd.Copy();//復制結構 Tableflag.Clear();//清除臨時數據 foreach (DataRow dr in tableAd.Rows) { if (dr["ParentId"].ToString().Equals("17")) { DataRow temPRow =TableTemp.NewRow(); //創建與該表相同架構的新行
tempRow["ClassName"] = dr["ClassName"];
tempRow["ParentId"] = dr["ParentId"];
tempRow["Name"] = dr["Name"];
tempRow["Pic"] = dr["Pic"];
tempRow["Url"] = dr["Url"];
tempRow["Sorts"] = dr["Sorts"];
TableTemp.Rows.Add(tempRow);
}
}
}
Two:

#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
//選取ParentId=17的所以行,并根據Sorts降序排序
TableTemp = SortDataTable(tableAd, "ParentId=17", "Sorts Desc", 2);
Three:

#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
//選取前7行數據
TableTemp = DtSelectTop(7, Table1);
新聞熱點
疑難解答