LINQ: Comparing specific values in two datatables

2019-08-31 04:58发布

This question already has an answer here:

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();

标签: c# linq
1条回答
Evening l夕情丶
2楼-- · 2019-08-31 05:37

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();
查看更多
登录 后发表回答