Linq - 子对象的where子句

Dav*_*vid 6 c# linq

鉴于以下课程:

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

public class City
{
  public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

假设Nation是聚合根,所以我只有a NationRepository而不是a CityRepository(因此Nation是Linq查询的起点).为了澄清,我的出发点将是一个IQueryable<Nation>对象.

我如何City根据以下逻辑编写一个返回对象集合的查询:

选择所有以"M"开头的City实例,Name其父级Nation名称为"UK"?

Jus*_*ner 14

你会做以下事情:

var results = NationRepository.Where(n => n.Name == "UK")
                              .SelectMany(n => n.Cities)
                              .Where(c => c.Name.StartsWith("M"));
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 8

像这样:

from n in Nation
where n.Name == "UK"
from c in n.Cities
where c.Name.StartsWith("M")
select c
Run Code Online (Sandbox Code Playgroud)