C#/.NET 条件合并两个DataTable
//先得到两个DataTable DataTable DataTable1 = SqlHelper.GetDataTable("select convert(char(5),id) As 'id' ,num from testSum"); DataTable DataTable2 = SqlHelper.GetDataTable("select '统计',Sum(num) from testSum"); //复制新建一个新的DataTable DataTable newDataTable = DataTable1.Clone(); //将DataTable1的数据加入到新的DataTable中 object[] obj = new object[newDataTable.Columns.Count]; for (int i = 0; i < DataTable1.Rows.Count; i++) { DataTable1.Rows[i].ItemArray.CopyTo(obj, 0); newDataTable.Rows.Add(obj); } //将DataTable2的数据加入到新的DataTable中 for (int i = 0; i < DataTable2.Rows.Count; i++) { DataTable2.Rows[i].ItemArray.CopyTo(obj, 0); newDataTable.Rows.Add(obj); } //显示到GridView中 GridView1.DataSource = newDataTable; GridView1.DataBind();
下边的话是我在项目中实用到的例子:
DataTable DtRegister = GetRegister("select * from registration",mysqlConnString).Tables[0]; DataTable DtSource = bll.GetList3(strWhere).Tables[0]; DataTable result = DtSource.Clone(); int i = 0; object[] obj=new object[DtSource.Columns.Count]; foreach (DataRow dataRow1 in DtSource.Rows) { foreach (DataRow dataRow2 in DtRegister.Rows) { if(dataRow1["HKID"].ToString().Equals(dataRow2["regist_number"].ToString())) { DtSource.Rows[i].ItemArray.CopyTo(obj,0); result.Rows.Add(obj); i++; } } }