Linq:在嵌套模型上执行Where()子句

4
这可能看起来很复杂,但我只是想从A中选择所有记录及其子记录,其中子记录存在某些条件。我正在寻找可以添加到变量A中的语法,以允许我过滤一堆条件(类似于规范模式?)
如果您有像这样的嵌套视图:
var a = from Arow in Atable
        where ???
        select new AViewModel {                    // (image Products)
            id = Arow.id,
            name = Arow.Name,
            Brows = (from Brow in Arow.Brows
                     select new BViewModel {       // (sold in different regions)
                         id = Brow.id,
                         name = Brow.Name,
                         Crows = (from Crow in Brow.Crows
                                  select new CViewModel { // (and in many stores)
                                      id = Crow.id,
                                      name = Crow.Name
                                  }
                     }
        };

以下是类似这样的来自网页的查询文本(规范模式?)。我们使用JQuery选择器用于操作符 (例如 ^= 表示“以…开头”)。

filter[] = { "Brow.Name = Joe", "Crow.Name = Kim" }

您好!这句话的英译中文大致是:“您如何使用这些条件筛选表达式 A?换句话说,您是否可以使用类似 a.Where() 的 where 表达式来过滤嵌套属性?”
var b = from row in a
        where a.Brow.Where(b => b.name == "Joe") &&
              a.Brow.Crow.Where(c => c.name == "Kim")
        select row;

我真正需要的是像这样的东西:
Select * 
from A join B on A.key = B.key join C on B.key = C.key -- propagated keys
where exists (select null from B where A.key = B.key and B.Name = "Joe") and
      exists (select null from C where A.key = C.key and C.Name = "Kim")

尤其是如果我能做到这点:
var result = a.Where(first).Where(second);
2个回答

7
你的“努力尝试”并不算太差。只需将 Where() 替换为 Any() 即可:
var b = from row in a
        where a.Brow.Any(b => b.name == "Joe") &&
              a.Brow.Crow.Any(c => c.name == "Kim")
        select row;

编辑添加:

不过,您可能希望进行不区分大小写的比较,例如:.Any(b => b.name.Equals("Joe", StringComparison.CurrentCultureIgnoreCase))


这几乎正确,或者是我做错了什么。a.Brow.Any()可以工作,但是使用a.Brow.Crow访问Crow失败了。然而,a.Brow.Any(p => p.Crow.Any(c => c.name == "Kim"))看起来非常有前途。 - Zachary Scott

2

或者为了好玩,你也可以使用lambda等效写法:

var b = a.where(x => x.Brow.Any(b => b.name == "Joe") 
                     && x.Brow.Crow.Any( c => c.name == "Kim")
         .Select(y => y.row);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接