简体   繁体   English

Linq - 关于子 object 的 where 子句

[英]Linq - where clause on child object

Given the following classes:给定以下类:

public class Nation
{
  public string Name { get; set; }
  public IEnumerable<City> Cities { get; private set; }
}

public class City
{
  public string Name { get; set; }
}

Assume Nation is the aggregate root and so I only have a NationRepository and not a CityRepository (thus Nation is the starting point for Linq queries).假设Nation是聚合根,所以我只有一个NationRepository而不是CityRepository (因此Nation是 Linq 查询的起点)。 To clarify, my starting point would be an IQueryable<Nation> object.澄清一下,我的出发点是IQueryable<Nation> object。

How would I write a query which returns a collection of City objects according to the following logic:我将如何编写一个根据以下逻辑返回City对象集合的查询:

Select all City instances whose Name begins with 'M' whose parent Nation 's name is 'UK'? Select Name以“M”开头且父Nation名称为“UK”的所有City实例?

You would do the following:您将执行以下操作:

var results = NationRepository.Where(n => n.Name == "UK")
                              .SelectMany(n => n.Cities)
                              .Where(c => c.Name.StartsWith("M"));

Like this:像这样:

from n in Nation
where n.Name == "UK"
from c in n.Cities
where c.Name.StartsWith("M")
select c
var result = nations.Where(n => n.Name == "UK")
                    .SelectMany(n => n.Cities)
                    .Where(c => c.Name.StartsWith("M"));

EDIT: Since @Justin Niessner beat me... maybe nest the second where clause编辑:因为@Justin Niessner 打败了我......也许嵌套第二个 where 子句

var result = nations.Where(n => n.Name == "UK")
                    .SelectMany(n => n.Cities.Where(c => c.Name.StartsWith("M"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM