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

标签 c# linq entity-framework

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

    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/

相关文章:

c# - WCF 服务引用使用 XmlSerializer 创建临时动态程序集

c# - params object[] 方法参数装箱了吗?

c# - 显示按日期排序的数据

C# List.Contains 在应该返回 true 时确实返回 true

c# - 为什么 Entity Framework 没有将我的集合加载到基类中?

c# - 如何在我的程序中记录从 DbContext.SaveChanges() 生成的 SQL?

c# - SFML.net 中的 SFML C++ getSize() 和 sprite.move()

c# - WindowsService的简单安装

c# - 在 LinQ Lambda Join 中检索索引

c# - 通过将表名、列名和值作为参数从实体进行动态 Linq SearchFor