两个结构一样的DataTable合并
NET 2.0 以上版本直接有 DataTable.Merge 方法:
http://msdn.microsoft.com/zh-cn/library/fk68ew7b.aspx
.NET Framework 类库
DataTable.Merge 方法
将指定的 DataTable 与当前的 DataTable 合并。
命名空间: System.Data
程序集: System.Data(在 System.Data.dll 中)
或者:
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
DataTable newDataTable = DataTable1.Clone();
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);
}
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
DataTable2.Rows[i].ItemArray.CopyTo(obj,0);
newDataTable.Rows.Add(obj);
}
//或者
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
object[] obj = new object[DataTable1 .Columns.Count];
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
DataTable2.Rows[i].ItemArray.CopyTo(obj,0);
DataTable1.Rows.Add(obj);
}
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
DataTable newDataTable = DataTable1.Clone();
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);
}
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
DataTable2.Rows[i].ItemArray.CopyTo(obj,0);
newDataTable.Rows.Add(obj);
}
//或者
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
object[] obj = new object[DataTable1 .Columns.Count];
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
DataTable2.Rows[i].ItemArray.CopyTo(obj,0);
DataTable1.Rows.Add(obj);
}
两个结构不同的DataTable合并
view plaincopy to clipboardprint?
/// <summary>
/// 将两个列不同的DataTable合并成一个新的DataTable
/// </summary>
/// <param name="dt1">Table表1</param>
/// <param name="dt2">Table表2</param>
/// <param name="DTName">合并后新的表名</param>
/// <returns></returns>
private DataTable UniteDataTable( DataTable dt1 ,DataTable dt2 ,string DTName)
{
DataTable dt3 = dt1.Clone();
for( int i = 0 ;i < dt2.Columns.Count ;i ++ )
{
dt3.Columns.Add( dt2.Columns[i].ColumnName ) ;
}
object[] obj = new object[dt3.Columns.Count];
for (int i = 0; i < dt1.Rows.Count; i++)
{
dt1.Rows[i].ItemArray.CopyTo(obj,0);
dt3.Rows.Add(obj);
}
if( dt1.Rows.Count >= dt2.Rows.Count )
{
for( int i = 0 ;i < dt2.Rows.Count ;i++ )
{
for( int j = 0 ;j < dt2.Columns.Count ;j ++ )
{
dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ;
}
}
}
else
{
DataRow dr3 ;
for( int i = 0 ;i < dt2.Rows.Count - dt1.Rows.Count ;i ++ )
{
dr3 = dt3.NewRow() ;
dt3.Rows.Add( dr3 ) ;
}
for( int i = 0 ;i < dt2.Rows.Count ;i++ )
{
for( int j = 0 ;j < dt2.Columns.Count ;j ++ )
{
dt3.Rows[i][j+dt1.Columns.Count] = dt2.Rows[i][j].ToString() ;
}
}
}
dt3.TableName = DTName ;
return dt3 ;
}
本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/articles/1535518.html,如需转载请自行联系原作者