Compare two same datatable and fetch the missing records

These days LINQ is a very essential to get desired output. Recently I’ve faced one problem where i’ve to compare 2 same datatable and get the missing records from it. After googled I’ve found solution and here is the code snippet

DataTable dt1, dt2;
dt1 = //Fill Datatable;
dt2 = //Fill Datatable;
var matched = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on table1.Field(“ID”) equals table2.Field(“ID”)
select table1;
var missing = from table1 in dt1.AsEnumerable()
where !matched.Contains(table1)
select table1;
DataTable dtMissing = missing.CopyToDataTable();
int missingCount = dtMissing.Rows.Count;
DataTable dtMatching = matched.CopyToDataTable();
int matchingCount = dtMatching.Rows.Count;

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>