0

I have two datatables.

datatable 1 has data with columns FirstName, LastName, DOB, Gender datatable 2 has data with columns CustomerID, FirstName, LastName, DOB, Gender

I want to compare the firstName, LastName, DOB and gender in datatable 1 and 2, and if there is a match, load that row in datatable 2 into a new datatable.

Below is what I am using, I can compare with Firstname, but I want to add the lastname, DOB and gender. Please can you show me how I can do that?

I want to do it such that if firstname, lastname, dob and gender match then return that matching row in datatable 2. The column length between the tables are different.

DataTable dtMerged = (from a in dataTable.AsEnumerable()
                                  join b in dt.AsEnumerable()
                                  on a["Forename"].ToString() equals b["FirstName"].ToString()
                                  into g
                                  where g.Count() > 0
                                  select a).CopyToDataTable();

            dtMerged.AsDataView();
edcoder
  • 503
  • 1
  • 5
  • 19
  • sorry @Anas, its not a duplicate. I did go through that answer but that one compares all columns, but I want to compare specific columns. – edcoder May 30 '19 at 07:12
  • 1
    @edcoder yes it's duplicate indeed. may not be exact one. – Rahul May 30 '19 at 07:33

1 Answers1

2

Try this

DataTable dtMerged = dataTable.AsEnumerable()
    .Where(ra => dt.AsEnumerable()
    .Any(rb => rb.Field<string>("firstname") == ra.Field<string>("firstname")
      && rb.Field<string>("lastname") == ra.Field<string>("lastname")
      && rb.Field<DateTime>("dob") == ra.Field<DateTime>("dob")
      && rb.Field<string>("gender") == ra.Field<string>("gender")))
              .CopyToDataTable();
Anas Alweish
  • 2,818
  • 4
  • 30
  • 44
Shyam Vemula
  • 591
  • 2
  • 14