SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

How to Compare Two Datatable and get common records in other DataTable in C#?

I have Two DataTable with Two columns in each Table. Now, i want to Compare these Two DataTable and the Matching rows in Third DataTable in C#.

Eg:

DataTableA
ColA1   ColA2
 1      sampletext1
 2      sampletext2
 4      sampletext4

DataTableB
ColB1   ColB2
 1      sampletext1
 2      sampletext2
 3      sampletext3

DataTableC
ColC1  ColC2
 1      sampletext1
 2      sampletext2

I have tried it using for loop but it slows down. Any other alternative.

Upvotes: 0

Views: 6725

Answers (4)

Murugavel
Murugavel

Reputation: 279

Use like below. It will work faster

var matched = from table1 in dt1.AsEnumerable()
                      join table2 in dt2.AsEnumerable() on table1.Field<string>("sno") equals table2.Field<string>("sno")
                      where table1.Field<string>("name") == table2.Field<string>("name")
                      select table1;
        if (matched.Count()>0)
        {
            DataTable dtt = matched.CopyToDataTable();
        }

Dont forget to mention as answer if it helps.

Upvotes: 1

Vikram Jain
Vikram Jain

Reputation: 5588

First use merge function merge two datatable, and finnaly for loop on datatable and find result by select function:

dt1 = dt.Copy();
dt1.Merge(dt2);

//Here match condition third Data table
for(int i=0; i <=dt1.rows; i++)
{
  DataRow[] foundRows = dt3.Select("page_name='" + dt1.[i]['colname'] + "'");
  //function or code here;
}

Upvotes: 0

aads
aads

Reputation: 2495

Not sure what exactly your matching criteria is. below might be helpful.

refer this

public static DataTable CompareTwoDataTable(DataTable dt1, DataTable dt2)
{ 
  dt1.Merge(dt2);
  DataTable d3 = dt2.GetChanges();
  return d3;
}

Upvotes: 2

Md. Parvez Alam
Md. Parvez Alam

Reputation: 4596

for(i=0;i<dt1.rows.count;i++)
{
   if (dt2.rows.count > i)
    {
         if((dt1.rows[i][1] == dt2.rows[i][1])  && (dt1.rows[i][2] == dt2.rows[i][2]))
           {
               dt3.rows.add(dt.rows[i])
           } 

     }
 }

Upvotes: 0

Related Questions