Arbaaz
Arbaaz

Reputation: 321

Query to find out the duplicate rows among two DataTable?

I have an excel sheet with columns:

Id,Data

I have a table in sql server database:

Id,Data

I have derived rows of both in two different DataTables, now I want to detect rows which are common in both excel and database table and store the duplicates in another DataTable. Something like this:

OleDbCommand command1 = new OleDbCommand("select * from [Sheet1$]",connection);
DataTable dt2 = new DataTable();
try
{
    OleDbDataAdapter da2 = new OleDbDataAdapter(command1);
    da2.Fill(dt2);
}
catch { }

Upvotes: 2

Views: 2321

Answers (2)

roman
roman

Reputation: 117380

If you want to find duplicates, you can try this

var result = table1.AsEnumerable().Intersect(table2.AsEnumerable()).Select(x => x);

If you want to eliminate duplicates from union, you can try this

var result = table1.AsEnumerable().Union(table2.AsEnumerable()).Select(x => x);

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

try out using linq way like this

var matched = from table1 in dt1.AsEnumerable()
               join table2 in dt2.AsEnumerable() on 
             table1.Field<int>("ID") equals table2.Field<int>("ID")
             where table1.Field<string>("Data") == table2.Field<string>("Data")
             select table1;

Upvotes: 1

Related Questions