gpt4 book ai didi

c# - 将两个不同类型的列表匹配在一起

转载 作者:太空狗 更新时间:2023-10-29 22:33:08 25 4
gpt4 key购买 nike

我有两个表,每个表都有自己的模型...

    class FamilyMan
{
public int family_ID {get; set;}

public string name {get; set;}
public string fav_color {get; set;}
}

class BusinessMan
{
public int work_ID {get; set;}

public string name {get; set;}
public string fav_color {get; set;}

//unrelated data etc
public string job_title {get; set;}
}

...我希望能够根据 namefav_color 将所有 FamilyMan 与匹配的 BusinessMan 匹配。

我目前有类似的东西:

    //fill lists from database
var family_list = dbContext.FamilyMen.ToList();
var busy_list = dbContext.BusinessMen.ToList();
//create empty dict for matching the two types
var matches = new Dict<FamilyMan, BusinessMan>();


foreach (FamilyMan fam_man in family_list) {
foreach (BusinessMan busy_man in busy_list) {
//if both names and colors match, consider them a matching
//object and add them each to the dict
if (fam_man.name == busy_man.name &&
fam_man.color == busy_man.color) {
matches_MtO[fam_man] = busy_man;
}
}
}

但这需要相当长的时间才能完成。

我也研究过使用 foreach 遍历一个列表,然后使用 LINQs FirstOrDefault 来匹配它们,但效率似乎差不多。

是否有更好的方法将 FamilyManBusinessMan 匹配在一起?

最佳答案

像这样的 linq 查询会更快吗:

var matches = (
from f in family_list
join b in busy_list
on f.color == b.color
&& f.name == b.name
select new {f, b}
);

关于c# - 将两个不同类型的列表匹配在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14283349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com