private DataTable Join(DataTable first, DataTable second, DataColumn[] FJC, DataColumn[] SJC)
{
//将两个表根据某列关联生成一个表
DataTable table = new DataTable("Join");
try
{
DataSet ds = new DataSet();
DataTable[] dt ={ first.Copy(), second.Copy() };
//将两个表存入到Dataset中
ds.Tables.AddRange(dt);
DataColumn[] parentcolumns = new DataColumn[FJC.Length];
for (int i = 0; i < parentcolumns.Length; i++)
{
parentcolumns[i] = ds.Tables[0].Columns[FJC[i].ColumnName];
}
DataColumn[] childcolumns = new DataColumn[SJC.Length];
for (int i = 0; i < childcolumns.Length; i++)
{
childcolumns[i] = ds.Tables[1].Columns[SJC[i].ColumnName];
}
//设置两表中的关系.
DataRelation r = new DataRelation(string.Empty, parentcolumns, childcolumns, false);
ds.Relations.Add(r);
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}
for (int i = 0; i < second.Columns.Count; i++)
{
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 + "_Second", second.Columns[i].DataType);
}
}
table.BeginLoadData();
foreach (DataRow firstrow in ds.Tables[0].Rows)
{
DataRow[] childrows = firstrow.GetChildRows(r);
if (childrows != null && childrows.Length > 0)
{
object[] parentarray = firstrow.ItemArray;
foreach (DataRow secondrow in childrows)
{
object[] secondarray = secondrow.ItemArray;
object[] joinarray = new object[parentarray.Length + secondarray.Length];
Array.Copy(parentarray, 0, joinarray, 0, parentarray.Length);
Array.Copy(secondarray, 0, joinarray, parentarray.Length, secondarray.Length);
table.LoadDataRow(joinarray, true);
}
}
else
{
object[] parentarray = firstrow.ItemArray;
DataRow secondrow=second.NewRow();
object[] secondarray = secondrow.ItemArray;
object[] joinarray = new object[parentarray.Length + secondarray.Length];
Array.Copy(parentarray, 0, joinarray, 0, parentarray.Length);
Array.Copy(secondarray, 0, joinarray, parentarray.Length, secondarray.Length);
table.LoadDataRow(joinarray, true);
}
}
table.EndLoadData();
}
catch (Exception e)
{
Response.Write(e.ToString());
}
return table;
}
private DataTable Join(DataTable first, DataTable second, DataColumn FJC, DataColumn SJC)
{
return Join(first, second, new DataColumn[] { FJC }, new DataColumn[] { SJC });
}
private DataTable Join(DataTable first, DataTable second, string FJC, string SJC)
{
return Join(first, second, new DataColumn[] { first.Columns[FJC] }, new DataColumn[] { first.Columns[SJC] });
}