public static DataTable Join(DataTable First, DataTable Second, DataColumn[] FJC, DataColumn[] SJC)
{
DataTable table = new DataTable("Join");
using (DataSet ds = new DataSet())
{
ds.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });
DataColumn[] First_columns = new DataColumn[FJC.Length];
for (int i = ; i < First_columns.Length; i++)
{
First_columns[i] = ds.Tables[].Columns[FJC[i].ColumnName];
}
DataColumn[] Second_columns = new DataColumn[SJC.Length];
for (int i = ; i < Second_columns.Length; i++)
{
Second_columns[i] = ds.Tables[].Columns[SJC[i].ColumnName];
}
DataRelation r = new DataRelation(string.Empty, First_columns, Second_columns, false);
ds.Relations.Add(r); for (int i = ; i < First.Columns.Count; i++)
{
table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);
} for (int i = ; i < Second.Columns.Count; i++)
{ //看看有没有重复的列,如果有在第二个DataTable的Column的列明后加_Second
if (!table.Columns.Contains(Second.Columns[i].ColumnName))
table.Columns.Add(Second.Columns[i].ColumnName, Second.Columns[i].DataType);
else
table.Columns.Add(Second.Columns[i].ColumnName + "_1", Second.Columns[i].DataType);
}
table.BeginLoadData(); int itable2Colomns = ;
if (ds.Tables[].Rows.Count > ) {
itable2Colomns = ds.Tables[].Rows[].ItemArray.Length;
} foreach (DataRow firstrow in ds.Tables[].Rows)
{
//得到行的数据
DataRow[] childrows = firstrow.GetChildRows(r);//第二个表关联的行
if (childrows != null && childrows.Length > )
{
object[] parentarray = firstrow.ItemArray;
foreach (DataRow secondrow in childrows)
{
object[] secondarray = secondrow.ItemArray;
object[] joinarray = new object[parentarray.Length + secondarray.Length];
Array.Copy(parentarray, , joinarray, , parentarray.Length);
Array.Copy(secondarray, , joinarray, parentarray.Length, secondarray.Length);
table.LoadDataRow(joinarray, true);
}
}
else//如果有外连接(Left Join)添加这部分代码
{
object[] table1array = firstrow.ItemArray;//Table1
object[] table2array = new object[itable2Colomns];
object[] joinarray = new object[table1array.Length + itable2Colomns];
Array.Copy(table1array, , joinarray, , table1array.Length);
Array.Copy(table2array, , joinarray, table1array.Length, itable2Colomns);
table.LoadDataRow(joinarray, true);
DataColumn[] dc = new DataColumn[];
dc[] = new DataColumn("");
}
}
table.EndLoadData();
}
return table;
}