DataTable dt;//不为空的DataTableDataRow[] rows=dt.Select(" c_user_name ='123456' ");//获取datarow[]类型
现需要将查询出来的datarow[]类型再次转换为DataTable时,可以用到下面方法:
/// <summary>/// datarow[]转换成datatable/// </summary>/// <param name="rows"></param>/// <returns></returns>public DataTable ToDataTable(DataRow[] rows){if (rows == null || rows.Length == 0) return null;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);}