c# - 在 C# 中比较两个数据集

标签 c# .net-2.0 dataset

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

例如:

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() + "')");
                    }
                }
            }
        }  

以上代码无效。请纠正我的问题。

谢谢

最佳答案

使用合并方法:

Dataset2.Merge(Dataset1);

这会将任何在 Dataset1 中但不在 Dataset2 中的记录插入到 Dataset2 中。注意:您最初的问题表明您需要从 Dataset1 插入记录或更新匹配记录,但您的评论似乎表明您实际上并不需要进行更新。 Merge 方法只会插入 Dataset1 中的新记录。

关于c# - 在 C# 中比较两个数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259855/

相关文章:

c# - 当内容超出范围时在文本框中显示滚动条C#

c# - 使用 group by 获取结果

c# - 如何从另一个表格打开一个新表格

matlab - 何时在 Matlab 中使用单元格、矩阵或表格

asp.net - 如何通过Web服务从返回的数据集中删除 "diffgr:before"内容

mysql - 如何在mysql的单个查询中获取选定的值组集?

c# - 删除文件 vs 目录 + 重新创建性能

c# - 动态创建winforms控件

c# - 是否有不区分大小写的 string.Replace 替代方法?

.net - .NET Framework可以在Win98上使用吗?