Here, I have two tables such as dtTable1 and dtTable2. It has the following records.
dtTable1:
ItemID Specification Amount
--------- --------------- ---------
1 A 10
1 B 20
1 C 30
dtTable2:
ItemID Specification Amount
--------- --------------- ---------
1 A 10
1 B 20
1 C 30
2 A 10
2 B 20
3 A 10
3 B 20
Here I want to compare these two tables. If dtTable1 records present in dtTable2 (consider only ItemID) then remove the corresponding rows which has the ItemID same as dtTable1 .
Solution 1
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace console_poc
{
class Program
{
static void Main(string[] args)
{
DataTable dtTable1 = new DataTable();
dtTable1.Columns.Add("ItemID", typeof(int));
for (int i = 0; i <= 5; i++)
dtTable1.Rows.Add(i); // table 1 contains { 0,1,2,3,4,5,7}
DataTable dtTable2= new DataTable();
dtTable2.Columns.Add("ItemID", typeof(int));
dtTable2.Rows.Add(1);
dtTable2.Rows.Add(5);
dtTable2.Rows.Add(6); // table 2 contains { 1,5,6}
var temp = dtTable2.Copy();
foreach (DataRow DR in temp.Rows)
{
int index = temp.Rows.IndexOf(DR);
foreach (DataRow row in dtTable1.Rows)
if (DR["ItemID"].ToString() == row["ItemID"].ToString())
{
dtTable2.Rows.RemoveAt(index);
}
}
dtTable2.AcceptChanges(); // now table 2 contains {6}
}
}
}
Conversion Conversion Emoticon Emoticon