连接列表<对象>list< string>

本文关键字:list string 对象 列表 连接 | 更新日期: 2023-09-27 17:51:16

我有List<object>List<string>的记录。

以下是我的记录列表。

var listContributionDetailsToBeUpdated = new List<ContributionDetailModel> 
{
    new ContributionDetailModel { EmployeeNumber="1", EmployeeFirstName="david", EmployeeLastName="k", NHIPNumber="nhi-100" },
    new ContributionDetailModel { EmployeeNumber="2", EmployeeFirstName="xavior", EmployeeLastName="f",NHIPNumber="nhi-101"},
    new ContributionDetailModel { EmployeeNumber="3", EmployeeFirstName="george", EmployeeLastName="s", NHIPNumber="nhi-102" },
    new ContributionDetailModel { EmployeeNumber="4", EmployeeFirstName="pandit", EmployeeLastName="h",NHIPNumber="nhi-103"},
    new ContributionDetailModel { EmployeeNumber="5", EmployeeFirstName="zania", EmployeeLastName="d", NHIPNumber="nhi-104" }
};
var updatedRecored = new List<string> { "nhi-100", "nhi-101", "nhi-102" };

谁能帮我把这两个列表内连起来

连接列表<对象>list< string>

这很简单。只需从贡献详情中选择NHIPNumber作为加入键:

var result = from c in listContributionDetailsToBeUpdated
             join r in updatedRecored on c.NHIPNumber equals r
             select c;

方法语法:

var result = listContributionDetailsToBeUpdated
     .Join(updatedRecored, c => c.NHIPNumber, r => r, (c, r) => c);

你也可以用过滤代替连接,但这不是最优的方式,因为连接是一个集合操作,它使用内部查找连接集合。通过简单的过滤,你将得到复杂度为O(N*M)而不是O(N+M)

var result = listContributionDetailsToBeUpdated
     .Where(c => updatedRecored.Contains(c.NHIPNumber));

以下也可以:

var result = listContributionDetailsToBeUpdated.Where(x => updatedRecored.Contains(x.NHIPNumber));