如何使用LINQ匹配c#中两个列表中的特定属性

时间:2015-07-04 14:16:32

标签: c# linq entity-framework

我正在为家庭项目使用Entity Framework。

例如,假设我有两个列表: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;
    }

1 个答案:

答案 0 :(得分:1)

您可以使用&&运算符简单地对两个属性进行相等性检查,例如:

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();
相关问题