Click here to Skip to main content
15,913,156 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have 2 datatables.each of them has column "ID".I want to get those IDs that are present in both datatables.
How should i do it.
i also need to put the extracted rows in a new datatable.how do i do that?
Posted
Updated 12-Apr-12 3:16am
v2

hey,

u get common ids like following

DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dt.Rows.Add(4);
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");

dt1.Rows.Add(1);
dt1.Rows.Add(2);
dt1.Rows.Add(3);



foreach (DataRow dr in dt.Rows)
{
foreach (DataRow dr1 in dt1.Rows)
{
if (dr[0].ToString() == dr1[0].ToString())
Response.Write(dr[0].ToString());
}
}

Best Luck
Happy Coding
 
Share this answer
 
Comments
sapna62 12-Apr-12 9:08am    
thanks Nilesh!
sapna62 12-Apr-12 9:11am    
But,I am working on windows application.I can not write response.write and i need to send these selected rows to a data table.how do i do that?
This is a walk which is effecient. If you use the foreach, as the tables get larger you increase the time by the square (O(x square)). This solution is linear (O(x)):

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
int c1 = 0;
int c2 = 0;

while (c1 < dt1.Rows.Count  && c2 < dt2.Rows.Count)
{
    if ((int)dt1.Rows[c1][0] == (int) dt1.Rows[c2][0])
    {
        //Match found
        c1++;
        c2++;
    }
    else if ((int)dt1.Rows[c1][0] > (int)dt1.Rows[c2][0])
    {
        //Missing row in dt1
        c2++;
    }
    else
    {
        //Missing row in dt2
        c1++;
    }
}

if (c1 < dt1.Rows.Count)
{
    //Missing rows at the end in dt2
}
if (c2 < dt2.Rows.Count)
{
    //Missing rows at the end in dt1
}


If you want to have the results in a table then:

dt3.Rows.Add(dt1.Rows[c1]);


Where dt3 is another table you have defined.
 
Share this answer
 
v4

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