过滤GroupJoin查询

时间:2012-11-13 17:41:52

标签: c# asp.net-mvc asp.net-mvc-3 linq linq-to-entities

我有一个GroupJoin Query,返回如下结果:

IEnumerable<ICD.ViewModels.HomeSearchViewModel> query = ICDUnitOfWork.AlphaGroups.Find()
    .GroupJoin(ICDUnitOfWork.Alphas.Find(),
        a => a.AlphaGroupID,
        g => g.AlphaGroupID,
        (alphaGroups, alphas) =>
            new ICD.ViewModels.HomeSearchViewModel
            {
                AlphaGroups = alphaGroups,
                Alphas = alphas
            });

Alphas为IEnumerable,AlphaGroup包含多个Alpha。他们都有一个名为“标题”的属性。我需要根据包含字符串“baby”的“Title”属性过滤结果。我怎么能做到这一点?

编辑:我还应该提到,如果某个特定的alpha组标题包含“baby”,则应显示所有具有AlphaGroupID的相应Alpha。

2 个答案:

答案 0 :(得分:1)

如果您使用的是Entity Framework&gt; = 4,则Contains将有效:

.Where(row => 
    row.AlphaGroups.Title.Contains("baby") 
        || row.Alphas.Any(alpha => alpha.Title.Contains("baby"))
 );

修改已更新,可预先过滤分组中的字母。最终过滤器排除不包含alphas的行(表示既不 AlphaGroup标题,也不包含任何 Alpha包含字符串)。

IEnumerable<ICD.ViewModels.HomeSearchViewModel> query = ICDUnitOfWork.AlphaGroups.Find()
    .GroupJoin(ICDUnitOfWork.Alphas.Find(),
        a => a.AlphaGroupID,
        g => g.AlphaGroupID,
        (alphaGroups, alphas) =>
            new ICD.ViewModels.HomeSearchViewModel
            {
                AlphaGroups = alphaGroups,
                Alphas = alphas.Where(alpha 
                    => alphaGroups.Title.Contains("baby")
                        || alpha.Title.Contains("baby"))
            });
    .Where(row => row.Alphas.Any());

答案 1 :(得分:1)

会推荐.Any(),因为它可以映射到嵌套联盟,而只是过滤预加入

尝试

IEnumerable<ICD.ViewModels.HomeSearchViewModel> query = 
     ICDUnitOfWork.AlphaGroups.Find()
                  .Where(g => g.Title.Contains("baby"))
                  .GroupJoin(ICDUnitOfWork.Alphas.Find()
                                          .Where(a => a.Title.Contains("baby"),
                             a => a.AlphaGroupID,
                             g => g.AlphaGroupID,
                             (alphaGroups, alphas) =>
                                new ICD.ViewModels.HomeSearchViewModel
                                 {
                                  AlphaGroups = alphaGroups,
                                  Alphas = alphas
                                 }).AsEnumerable();