比较两个DataSet,并产生增量数据/// <summary>
/// 比较两个DataSet,并产生增量数据
/// </summary>
/// <param name="oldDataSet">原始DataSet</param>
/// <param name="nowDataSet">现有DataSet</param>
/// <param name="primaryKey">原始DataSet和现有DataSet Tables[0]的主键</param>
/// <returns>DataSet</returns>
public DataSet CompareDataSet(DataSet oldDataSet, DataSet nowDataSet, string primaryKey)
{
//更新nowDataSet中的所有行,使之状态为DataRowState.UnChanged
nowDataSet.AcceptChanges();
//要返回的DataSet
DataSet newDataSet = new DataSet();
//设置oldDataSet 和 newDataSet Tables[0] 的主键
DataColumn dcOld = oldDataSet.Tables[0].Columns[primaryKey];
DataColumn dcNow = nowDataSet.Tables[0].Columns[primaryKey];
//设置主键
oldDataSet.Tables[0].PrimaryKey = new DataColumn[1] { dcOld };
nowDataSet.Tables[0].PrimaryKey = new DataColumn[1] { dcNow };
string primaryValue = string.Empty;
string where = string.Empty;
foreach (DataRow drNow in nowDataSet.Tables[0].Rows)
{
//每行数据中,主键列所对应的值
primaryValue = drNow[primaryKey].ToString();
where = primaryKey + " = '" + primaryValue + "'";
//在oldDataSet 中查找和主键相同的行
DataRow[] drOld = oldDataSet.Tables[0].Select(where);
if (drOld.Length == 0)
{
drNow.SetModified();
}//说明nowDataSet中的这行数据是新增加的数据
else
{
for (int i = 0; i < drNow.ItemArray.Length; i++)
{
if (drNow.ItemArray.GetValue(i).ToString().Equals(drOld[0].ItemArray.GetValue(i).ToString()) == false)
{
drNow.SetModified();
break;
}//说明nowDataSet中的这行数据是修改过的数据
}
}//判断两行中的每一列是否相等
}
//装载DataRowState为 Modified的行
newDataSet.Tables.Add(nowDataSet.Tables[0].GetChanges(DataRowState.Modified));
return newDataSet;
}