Reputation: 494
I'm curious how I can compare two data tables in C#. I have two data tables, data table one contains FirstName and LastName, data table 2 has Field1, Field2, First_Name, and Last_Name.
I want to find records that exist in data table 1 that do not exist in data table 2. Anyone ever done this before? Any help would be appreciated. Thank you!
Upvotes: 1
Views: 5654
Reputation: 26917
Using LINQ would be most natural, but you will need to convert away from the DataTable to use Except
.
var In_dt1_only = dt1.AsEnumerable().Select(r => new { first = r.Field<string>("First"), last = r.Field<string>("Last")}).Except(dt2.AsEnumerable().Select(r => new { first = r.Field<string>("First"), last = r.Field<string>("Last")}));
If you need the original DataRow
s, you can use a Where
instead:
var datarows_in_dt1_only = dt1.AsEnumerable().Where(dr1 => !dt2.AsEnumerable().Any(dr2 => dr1.Field<string>("First") == dr2.Field<string>("First") && dr1.Field<string>("Last") == dr2.Field<string>("Last")));
Upvotes: 4