/// <summary>
/// 将Table的类型合并
/// </summary>
/// <param name="dataSet">Table的集合</param>
/// <param name="keys">需要合并的Key</param>
/// <returns></returns>
public static DataTable MergeDataTable(DataSet dataSet, List<string> keys)
{
DataTable tableMerge = new DataTable();
// 创建Table Column
for (int i = 0; i < dataSet.Tables.Count; i++)
{
// 第一个表格,完全复制其内容
if (i == 0)
{
tableMerge = dataSet.Tables[0].Copy();
}
else
{
foreach (DataColumn dataColumn in dataSet.Tables[i].Columns)
{
// 重新添加一个Column
if (tableMerge.Columns[dataColumn.ColumnName] == null)
{
tableMerge.Columns.Add(dataColumn.ColumnName, dataColumn.DataType);
}
}
}
}
// 填充数据
DataTable dataTable = null;
bool flgEqual = true;
bool flgExists = false;
for (int i = 1; i < dataSet.Tables.Count; i++)
{
// 获取其中的Table
dataTable = dataSet.Tables[i];
// 循环Merge
foreach (DataRow dataRow in dataTable.Rows)
{
flgExists = false;
// 循环数据
foreach (DataRow dataRowMerge in tableMerge.Rows)
{
// 判断Key的值是否相等
flgEqual = true;
foreach (string key in keys)
{
if (dataRowMerge[key].ToString().Equals(dataRow[key].ToString()) == false)
{
flgEqual = false;
break;
}
}
// 如果值匹配了
if (flgEqual == true)
{
flgExists = true;
// 循环表单
foreach (DataColumn dataColumn in dataTable.Columns)
{
if (keys.Contains(dataColumn.ColumnName) == false
&& tableMerge.Columns.Contains(dataColumn.ColumnName) == true)
{
// 填充数据内容
dataRowMerge[dataColumn.ColumnName] = dataRow[dataColumn.ColumnName];
}
}
}
}
// 如果不存在改数据的内容,需要添加一个数据
if (flgExists == false)
{
DataRow newRow = tableMerge.NewRow();
// 循环表单
foreach (DataColumn dataColumn in dataTable.Columns)
{
// 填充数据内容
newRow[dataColumn.ColumnName] = dataRow[dataColumn.ColumnName];
}
// 添加数据
tableMerge.Rows.Add(newRow);
}
}
}
// 结果集返回
return tableMerge;
}
/// <summary>
/// 将Table的类型合并
/// </summary>
/// <param name="dataSet">Table的集合</param>
/// <returns></returns>
public static DataTable MergeDataTable(DataSet dataSet)
{
DataTable tableMerge = new DataTable();
DataTable dataTable = null;
if (dataSet.Tables.Count > 0)
{
tableMerge = dataSet.Tables[0].Copy();
int minRowCount;
for (int i = 1; i < dataSet.Tables.Count; i++)
{
dataTable = dataSet.Tables[i];
minRowCount = tableMerge.Rows.Count <= dataTable.Rows.Count
? tableMerge.Rows.Count : dataTable.Rows.Count;
foreach (DataColumn dataColumn in dataTable.Columns)
{
// 重新添加一个Column
if (tableMerge.Columns[dataColumn.ColumnName] == null)
{
tableMerge.Columns.Add(dataColumn.ColumnName, dataColumn.DataType);
}
}
for (int j = 0; j < minRowCount; j++)
{
foreach (DataColumn dataColumn in dataTable.Columns)
{
tableMerge.Rows[j][dataColumn.ColumnName] = dataTable.Rows[j][dataColumn.ColumnName];
}
}
if (tableMerge.Rows.Count < dataTable.Rows.Count)
{
DataRow newRow = null;
for (int j = tableMerge.Rows.Count; j < dataTable.Rows.Count; j++)
{
newRow = tableMerge.NewRow();
foreach (DataColumn dataColumn in dataTable.Columns)
{
newRow[dataColumn.ColumnName] = dataTable.Rows[j][dataColumn.ColumnName];
}
tableMerge.Rows.Add(newRow);
}
}
}
}
// 结果集返回
return tableMerge;
}