[英]Compare two datasets in 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() + "')");
}
}
}
}
上面的代碼不起作用。 請糾正我的問題。
謝謝
使用合並方法:
Dataset2.Merge(Dataset1);
這將在Dataset2中插入Dataset1中但數據集2中尚未存在的任何記錄。 注意:您的原始問題表明您需要插入記錄或更新數據集1中的匹配記錄,但您的注釋似乎表明您實際上不需要進行更新。 Merge方法僅從Dataset1插入新記錄。
DataSet data1
DataSet data2
data1.Merge(data2,true)
將data2
合並到data1
不會覆蓋具有相同主鍵的行,並在data1
添加具有不存在的主鍵的行。
data1.Merge(data2,false)
將data2
合並到data1
覆蓋所有行並添加新行
我認為您的錯誤是使用==
來比較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
}
}
將這兩個表(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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.