【问题标题】:How to match specific properties within two lists in c# using LINQ如何使用 LINQ 匹配 c# 中两个列表中的特定属性
【发布时间】:2015-07-04 22:24:08
【问题描述】:

我正在为一个家庭项目使用实体框架。

例如,假设我有两个列表:A 和 B

我需要能够根据两者之间的共同属性匹配列表A和B中的项目(选择列表A和B中具有相同价值和相同城市的所有房屋)

一个 House 在两个列表中可以有两个共同的属性(例如 Value 和 City),但其他一些属性可能不同(例如 HouseId),因此比较对象不会返回正确的匹配项。

我可以做两个嵌套的 foreach,但由于 LINQ 查询是为了使用 EF 查询数据库,所以我需要使用 LINQ。

这是我到目前为止所做的,但匹配不正确:

    public IEnumerable<ApplicationUser> GetMatchesForCurrentUser(ApplicationUser     currentUser)
    {
        var prematches = (from user in _memberRepository.All()
                          where user.Zone == currentUser.Zone &&
                                user.Time == currentUser.Time &&
                                user.HouseOfUser.Any(g => currentUser.HouseOfUser.Any(x => x.CityId == g.CityId))
                          select user).ToList();

        var matches = (from prematch in prematches
                       where prematch.HouseOfUser.Any(g => currentUser.HouseOfUser.Any(x => x.Value == g.Value))
                       select prematch).ToList();

        return matches;
    }

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:

    您可以使用&amp;&amp; 运算符简单地结合两个属性的相等性检查,例如:

    var prematches = (from user in _memberRepository.All()
                      where user.Zone == currentUser.Zone &&
                            user.Time == currentUser.Time &&
                            user.HouseOfUser.Any(g => currentUser.HouseOfUser.Any
                                                     (
                                                        x => x.CityId == g.CityId
                                                                &&
                                                             x.Value == g.Value
                                                     )
                                                )
                      select user).ToList();
    

    【讨论】:

    • @l3xn3 &amp;&amp; 的第二个操作数在您的代码中似乎被识别为Entities.HouseOfUser,而它应该是另一个布尔值(x.Value == g.Value 是一个布尔表达式)。也许有一个错字(括号放在错误的地方或某事),edit您对您尝试的代码的问题,我们也许能够发现问题
    • 我重写的时候代码有错别字,谢谢你的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2014-02-15
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多