比较C#中的两个数据集

我有两个数据集,我需要比较这两个数据集,如果一个表中不存在ID,那么我需要编写插入查询其他更新查询。

对于Ex:

Id in One dataset ID in second Dataset 1 1 2 2 3 4 

我需要将ID 3插入第二个数据集。

这是我的代码供您参考:

 if (ds.Tables[0].Rows.Count > 0 || clientDS.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { for (int j = 0; j < clientDS.Tables[0].Rows.Count; j++) { if (ds.Tables[0].Rows[i]["Id"].ToString() == clientDS.Tables[0].Rows[j]["Id"].ToString()) { client.GetSingleValue("update customers set Name='" + ds.Tables[0].Rows[i]["Name"].ToString() + "',ContactPerson= '" + ds.Tables[0].Rows[i]["ContactPerson"].ToString() + "',Address='" + ds.Tables[0].Rows[i]["Address"].ToString() + "',TinNo='" + ds.Tables[0].Rows[i]["TinNo"].ToString() + "',ContactNo='" + ds.Tables[0].Rows[i]["Contactno"].ToString() + "',Report= '" + ds.Tables[0].Rows[i]["Report"].ToString() + "',Sync=0,Ids='" + ds.Tables[0].Rows[i]["Id"].ToString() + "' where id='" + ds.Tables[0].Rows[i]["Id"].ToString() + "' "); } else { client.GetSingleValue("insert into customers(id,Name,ContactPerson,Address,TinNo,ContactNo,Report,Sync,Ids) values('" + ds.Tables[0].Rows[i]["Id"].ToString() + "', '" + ds.Tables[0].Rows[i]["Name"].ToString() + "','" + ds.Tables[0].Rows[i]["ContactPerson"].ToString() + "', '" + ds.Tables[0].Rows[i]["Address"].ToString() + "', '" + ds.Tables[0].Rows[i]["TinNo"].ToString() + "', '" + ds.Tables[0].Rows[i]["Contactno"].ToString() + "', '" + ds.Tables[0].Rows[i]["Report"].ToString() + "',0,'" + ds.Tables[0].Rows[i]["Id"].ToString() + "')"); } } } } 

上面的代码不起作用。 请纠正我的问题。

谢谢

我认为您的错误是使用==来比较Id字符串。 尝试使用Equals 。 我只是使用foreach并选择:

 foreach (DataRow row in ds.Tables[0].Rows) { string filter = string.Format("Id = '{0}'", row["Id"]); DataRow[] rows = clientDS.Tables[0].Select(filter); if (rows.length == 0) { // insert here } else { // update here } } 

使用合并方法:

 Dataset2.Merge(Dataset1); 

这将在Dataset2中插入Dataset1中但未包含在Dataset2中的任何记录。 注意:您的原始问题表明您需要插入记录或更新来自Dataset1的匹配记录,但您的注释似乎表明您实际上不需要进行更新。 Merge方法仅从Dataset1插入新记录。

 DataSet data1 DataSet data2 data1.Merge(data2,true) 

data2合并到data1不会覆盖具有相同主键的行,并在data1添加具有不存在的主键的行。

 data1.Merge(data2,false) 

data2合并到data1覆盖所有行并添加新行

将这两个表(DataTable实例)添加到DataSet中并添加关系。

DataSet ds = new DataSet(); ds.EnforceConstraints = false;

 DataTable dt1 = new DataTable("A"); DataTable dt2 = new DataTable("B"); dt1.Columns.Add("ID", typeof(int)); dt1.PrimaryKey = new DataColumn[] {dt1.Columns[0]}; dt1.Rows.Add(1); dt1.Rows.Add(2); dt1.Rows.Add(3); dt2.Columns.Add("ID", typeof(int)); dt2.Rows.Add(1); dt2.Rows.Add(2); dt2.Rows.Add(4); ds.Tables.Add(dt1); ds.Tables.Add(dt2); ds.Relations.Add("ID_REL", dt1.Columns[0], dt2.Columns[0]); foreach (DataRow r in ds.Tables["A"].Rows) { DataRow []child=r.GetChildRows("ID_REL"); Console.Write(r[0] + " " ); if (child.Length != 0) Console.WriteLine(child[0][0]); Console.WriteLine(); }