public DataTable UniteTwoDataTable(refDataTable dt1, refDataTable dt2, int colNum1, int colNum2)
{
DataTable dt = newDataTable();
if (dt1.Columns.Count < colNum1)
return dt;
if (dt2.Columns.Count < colNum2)
return dt;
//把keyName都加到ArrayList里
ArrayList rtn = newArrayList();
for (int i=0; i < dt1.Rows.Count; i++)
{
rtn.Add(dt1.Rows[i][colNum1].ToString());
}
for (int i = 0; i < dt2.Rows.Count; i++)
{
if (!rtn.Contains(dt2.Rows[i][colNum2].ToString()))
{
rtn.Add(dt2.Rows[i][colNum1].ToString());
}
}
rtn.Sort();
DataColumn dc;
DataRow dr;
//确定dt的栏位
dc = newDataColumn(dt1.Columns[colNum1].ColumnName.ToString(), typeof(string));
dt.Columns.Add(dc);
for (int j = 0; j < dt1.Columns.Count; j++)
{
if (j != colNum1)
{
dc = newDataColumn(dt1.Columns[j].ColumnName.ToString(), typeof(string));
dt.Columns.Add(dc);
}
}
for (int j = 0; j < dt2.Columns.Count; j++)
{
if (j != colNum2)
{
dc = newDataColumn(dt2.Columns[j].ColumnName.ToString(), typeof(string));
dt.Columns.Add(dc);
}
}
//给dt塞值
foreach (string keyName in rtn)
{
dr = dt.NewRow();
dr[0] = keyName;
int dtCount = 1;
for (int i = 0; i < dt1.Rows.Count; i++)
{
if (keyName.Contains(dt1.Rows[i][colNum1].ToString()))
{
for (int j = 0; j < dt1.Columns.Count; j++)
{
if (j != colNum1 )
{
if (dtCount < dt.Columns.Count)
{
dr[dtCount] = dt1.Rows[i][j].ToString();
}
dtCount++;
}
}
}
}
dtCount = dt1.Columns.Count;
for (int i = 0; i < dt2.Rows.Count; i++)
{
if (keyName.Contains(dt2.Rows[i][colNum2].ToString()))
{
for (int j = 0; j < dt2.Columns.Count; j++)
{
if (j != colNum2 )
{
if (dtCount < dt.Columns.Count)
{
dr[dtCount] = dt2.Rows[i][j].ToString();
}
dtCount++;
}
}
}
}
dt.Rows.Add(dr);
}
return dt;
}