datarow[]轉換成datatable
DataTable dt;//不為空的DataTable
DataRow[] rows=dt.Select(" c_user_name ='123456' ");//獲取datarow[]型別
現需要將查詢出來的datarow[]型別再次轉換為DataTable時,可以用到下面方法:
/// <summary>
/// datarow[]轉換成datatable
/// </summary>
///
/// <returns></returns>
public DataTable ToDataTable(DataRow[] rows)
{
if
DataTable tmp = rows[0].Table.Clone(); // 複製DataRow的表結構
foreach (DataRow row in rows)
{
tmp.Rows.Add(row.ItemArray); // 將DataRow新增到DataTable中
}
return tmp;
}
把一個表的DataRow[]轉換為另外的datatable(小技巧)
DataTable dt1 = new DataTable();
dt1.Columns.Add("a");
for (int i = 0; i < 10; i++)
{
DataRow dr1 = dt1.NewRow();
dr1["a"] = "1";
dt1.Rows.Add(dr1);
}
DataRow[] drw = dt1.Select("a =" + "1");
DataTable dt2 = new DataTable();
dt2 = dt1.Clone();
foreach (DataRow Drr in drw)
{
DataRow dr2 = dt2.NewRow();//如果在此直接用dt2.Rows.Add(Drr)會報錯,因為Drr的引用現在為dt1所用
dr2.ItemArray = Drr.ItemArray;
dt2.Rows.Add(dr2);
}