1

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!

bbcompent1
  • 494
  • 1
  • 10
  • 25
  • What have you tried? Post your code – maccettura Jun 29 '17 at 19:48
  • I am asking because this is something I have not done before, even links that clearly explain how it is done would be just fine. I've read some articles on Google but they did not make much sense or the author is a little confusing. I'm only asking for a breadcrumb here to start me on my way. Thanks! – bbcompent1 Jun 29 '17 at 19:52
  • You can use Linq: https://stackoverflow.com/questions/9289475/difference-of-two-datatables-in-c-sharp – naturalbornlazy Jun 29 '17 at 20:01

1 Answers1

4

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 DataRows, 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")));
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • Ok, that worked great, the only thing I had to do was swap the two data tables, then I got the expected result. Many thanks for your help! – bbcompent1 Jun 30 '17 at 11:12