C# 相同/不同的Datatable合并
作者:互联网
-
有时我们知道了两个DataTable1和DataTable2,我们希望将两个DataTable合并为一个新的DataTable,这就分为两种情况:DataTable1和DataTable2结构相同、DataTable1和DataTable2结构不同,下面分别介绍如何进行合并。
一、DataTable1和DataTable2结构相同的情况。
private DataTable SetDataTbble(DataTable table1, DataTable table2)
{
DataTable dataTable = table1.Clone();
object[] obj = new object[dataTable.Columns.Count];
for (int i = 0; i < table1.Rows.Count; i++)
{
table1.Rows[i].ItemArray.CopyTo(obj, 0);
dataTable.Rows.Add(obj);
}
for (int i = 0; i < table2.Rows.Count; i++)
{
table2.Rows[i].ItemArray.CopyTo(obj, 0);
dataTable.Rows.Add(obj);
}
return dataTable;
}二、DataTable1和DataTable2结构不同相同的情况。
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; //设置DT的名字
return dt3;
}
标签:Count,Rows,C#,合并,DataTable,int,dt3,dt2,Datatable 来源: https://www.cnblogs.com/P-Z-1/p/15539201.html