c# 对两个Datatable的结构相同进行合并:
1 Datatable db=null; 2 DataTable dt = ds.Tables[0]; 3 ////两个datatable进行合并 4 db = dt.Copy(); 5 DataRow[] foundRows = dt.Select(); 6 for (int i = 0; i < foundRows.Length;i++) 7 { 8 db.ImportRow(foundRows[i]); 9 }
//两个结构一样的DT合并
1 DataTable DataTable1 = new DataTable(); 2 DataTable DataTable2 = new DataTable(); 3 DataTable newDataTable = DataTable1.Clone(); 4 5 object[] obj = new object[newDataTable.Columns.Count]; 6 for (int i = 0; i < DataTable1.Rows.Count; i++) 7 { 8 DataTable1.Rows[i].ItemArray.CopyTo(obj,0); 9 newDataTable.Rows.Add(obj); 10 } 11 12 for (int i = 0; i < DataTable2.Rows.Count; i++) 13 { 14 DataTable2.Rows[i].ItemArray.CopyTo(obj,0); 15 newDataTable.Rows.Add(obj); 16 }
//两个结构不同的DT合并 :
1 /// <summary> 2 /// 将两个列不同的DataTable合并成一个新的DataTable 3 /// </summary> 4 /// <param name="dt1">表1</param> 5 /// <param name="dt2">表2</param> 6 /// <param name="DTName">合并后新的表名</param> 7 /// <returns></returns> 8 PRivate DataTable UniteDataTable( DataTable dt1 ,DataTable dt2 ,string DTName) 9 { 10 DataTable dt3 = dt1.Clone(); 11 for( int i = 0 ;i < dt2.Columns.Count ;i ++ ) 12 { 13 dt3.Columns.Add( dt2.Columns[i].ColumnName ) ; 14 } 15 object[] obj = new object[dt3.Columns.Count]; 16 17 for (int i = 0; i < dt1.Rows.Count; i++) 18 { 19 dt1.Rows[i].ItemArray.CopyTo(obj,0); 20 dt3.Rows.Add(obj); 21 } 22 23 if( dt1.Rows.Count >= dt2.Rows.Count ) 24 { 25 for( int i = 0 ;i < dt2.Rows.Count ;i++ ) 26 { 27 for( int j = 0 ;j < dt2.Columns.Count ;j ++ ) 28 { 29 dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ; 30 } 31 } 32 } 33 else 34 { 35 DataRow dr3 ; 36 for( int i = 0 ;i < dt2.Rows.Count - dt1.Rows.Count ;i ++ ) 37 { 38 dr3 = dt3.NewRow() ; 39 dt3.Rows.Add( dr3 ) ; 40 } 41 for( int i = 0 ;i < dt2.Rows.Count ;i++ ) 42 { 43 for( int j = 0 ;j < dt2.Columns.Count ;j ++ ) 44 { 45 dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ; 46 } 47 } 48 } 49 dt3.TableName = DTName ; //设置DT的名字 50 return dt3 ; 51 }
//多个结构相同的DataTable合并:
1 public DataTable GetAllEntrysDataTable() 2 { 3 DataTable newDataTable = GetEntrysDataTable(0).Clone(); 4 5 object[] obj = new object[newDataTable.Columns.Count]; 6 7 for (int i = 0; i < entryGroups.GetEntryGroupCount(); i++) 8 { 9 for (int j = 0; j < GetEntrysDataTable(i).Rows.Count; j++) 10 { 11 GetEntrysDataTable(i).Rows[j].ItemArray.CopyTo(obj, 0); 12 newDataTable.Rows.Add(obj); 13 } 14 } 15 return newDataTable;
资料引用:http://www.knowsky.com/539690.html