LINQ:比较两个数据表中的特定值 [英] LINQ: Comparing specific values in two datatables

查看:62
本文介绍了LINQ:比较两个数据表中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据表.

数据表1的数据具有FirstName,LastName,DOB,Gender列 数据表2的数据具有CustomerID,FirstName,LastName,DOB,Gender列

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

我想比较数据表1和2中的名字,姓氏,DOB和性别,如果匹配,则将数据表2中的该行加载到新的数据表中.

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.

下面是我正在使用的,可以与名字进行比较,但是我想添加姓氏,DOB和性别.请您告诉我我该怎么做?

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?

我要这样做,以便如果名字,姓氏,dob和性别匹配,然后在数据表2中返回该匹配行.表之间的列长是不同的.

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

推荐答案

尝试一下

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

这篇关于LINQ:比较两个数据表中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆