Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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


DTTable1:
 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.

I have tried following codes but cant solve the problem.


Code snippet 1:
C#
foreach (DataRow DR in DTTable2.Rows)
{
   if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
   {
        DTTable2.Rows.Remove(DR);
   }
}
DTTable2.AcceptChanges();

It showed the error, "Collection was modified; enumeration operation might not execute". So I used For Loop, It also not given the desired result.


Code Snippet 2:
C#
for (int i = 0; i < DTTable2.Rows.Count; i++)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
    {
        DTTable2.Rows.RemoveAt(i);
    }
}
DTTable2.AcceptChanges();



Code Snippet 3:
C#
List<datarow> rowsToDelete = new List<datarow>();
foreach (DataRow DR in DTTable2.Rows)
{
    if (DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        rowsToDelete.Add(DR);           
}

foreach (var r in rowsToDelete)
    DTTable2.Rows.Remove(r);



Code Snippet 4:
C#
DTTable2.Rows
    .Where(DR => DR["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
    .ToList()
    .ForEach(r => DTTable2.Rows.Remove(r));



Code Snippet 5:
C#
for (int i = DTTable2.Rows.Count - 1; i >= 0; i--)
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);



Code Snippet 6:
C#
int i = 0;
while (i < DTTable2.Rows.Count)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}



Code Snippet 7:
C#
var list = DTTable2.Rows.ToList();//create new list of rows
foreach (DataRow DR in list)
{
    //if bla bla bla
    DTTable2.Rows.Remove(DR);
}



Code Snippet 8:
C#
var result =  DTTable1.AsEnumerable()
                   .Where(row => !DTTable2.AsEnumerable()
                                         .Select(r => r.Field<int>("ItemID"))
                                         .Any(x => x == row.Field<int>("ItemID"))
                  ).CopyToDataTable();


Code snippet 9:

C#
for (int i = 0; i < DTTable2.Rows.Count; i++)
{
   if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[i]["ItemID"].ToString())
   {
      cmd = new SqlCommand("DELETE FROM DetailsTB WHERE ItemID = '" + DTTable2.Rows[i]["ItemID"].ToString() + "' ", con1);
      cmd.ExecuteNonQuery();
   }
}



But sometimes, the second row doesn't remove from the table. I get the final DataTable as
 ItemID     Specification    Amount
---------  ---------------  ---------
   1             B             20
   2             A             10
   2             B             20
   3             A             10
   3             B             20

How to solve this? What is the simplest method to do this?
All above code cant work.
some data are not deleted from DTTable2 that are also match with DTTable1.
These are only Few method here I write but i tried more than 20 method to do the same.
Posted
Updated 29-Nov-20 2:27am
v3

in your code snipet 6:
Code Snippet 6:
 Collapse | Copy Code
int i = 0;
while (i < DTTable2.Rows.Count)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}


try

Code Snippet 6:
for (int i=DTTable2.Rows.Count-1;i>=0;i--)
{
    if (DTTable2.Rows[i]["ItemID"].ToString() == DTTable1.Rows[0]["ItemID"].ToString())
        DTTable2.Rows.RemoveAt(i);
    else
        i++;
}


this might give you success
 
Share this answer
 
try this code..

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}
            
        
        }
    }
}
 
Share this answer
 
Comments
er.shoaib 23-Nov-13 0:07am    
This is a best code when I try on small no. of record in datatable but when I try it on large no. of record in datatable like 20 columns and hundreds of record then it still give me same record in both datatable. it not work on large no. of record in datatable.
er.shoaib 23-Nov-13 0:09am    
Thank you for giving me your valuable time
C#
for (int j = 0; j < DTTable2.Rows.Count; j++)
   {
      for (int m = 0; m < DTTable1.Rows.Count; m++)
       {
        if (DTTable2.Rows[m]["ItemID"].ToString() == DTTable1.Rows[j]                        ["ItemID"].ToString())
          {
              DTTable2.Rows.RemoveAt(m);
          }
       }
       DTTable2.AcceptChanges();
   }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900