/// <summary>
/// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable,表的字段不能重复,适用于多个表连接使用,和sql中的左右链接相识,直接就是两个表的对应连接起来,只是这里是记录条数相同id位置相同可以直接合并,合并后就可以得到连接后的表
/// </summary>
/// <param name="DataTable1">表1</param>
/// <param name="DataTable2">表2</param>
/// <param name="DTName">合并后新的表名,可以为空</param>
/// <returns>合并后的新表</returns>
private DataTable UniteDataTable(DataTable DataTable1, DataTable DataTable2, string DTName)
{
//克隆DataTable1的结构
DataTable newDataTable = DataTable1.Clone();
for (int i = 0; i < DataTable2.Columns.Count; i++)
{
//再向新表中加入DataTable2的列结构
newDataTable.Columns.Add(DataTable2.Columns[i].ColumnName);
}
object[] obj = new object[newDataTable.Columns.Count];
//添加DataTable1的数据
for (int i = 0; i < DataTable1.Rows.Count; i++)
{
DataTable1.Rows[i].ItemArray.CopyTo(obj, 0);
newDataTable.Rows.Add(obj);
}
if (DataTable1.Rows.Count >= DataTable2.Rows.Count)
{
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
for (int j = 0; j < DataTable2.Columns.Count; j++)
{
newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
}
}
}
else
{
DataRow dr3;
//向新表中添加多出的几行
for (int i = 0; i < DataTable2.Rows.Count - DataTable1.Rows.Count; i++)
{
dr3 = newDataTable.NewRow();
newDataTable.Rows.Add(dr3);
}
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
for (int j = 0; j < DataTable2.Columns.Count; j++)
{
newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
}
}
}
newDataTable.TableName = DTName; //设置DT的名字
return newDataTable;
}
评论列表: