鉴于以下类别:
public class Nation
{
public string Name { get; set; }
public IEnumerable<City> Cities { get; private set; }
}
public class City
{
public string Name { get; set; }
}
假设Nation
是聚合根,因此我只有NationRepository
而不是CityRepository
(因此Nation
是Linq查询的起点)。为了澄清,我的出发点是IQueryable<Nation>
对象。
如何根据以下逻辑编写一个返回City
个对象集合的查询:
选择City
以“M”开头的所有Name
个实例,其父级Nation
的名称为“英国”?
答案 0 :(得分:14)
您将执行以下操作:
var results = NationRepository.Where(n => n.Name == "UK")
.SelectMany(n => n.Cities)
.Where(c => c.Name.StartsWith("M"));
答案 1 :(得分:8)
像这样:
from n in Nation
where n.Name == "UK"
from c in n.Cities
where c.Name.StartsWith("M")
select c
答案 2 :(得分:2)
var result = nations.Where(n => n.Name == "UK")
.SelectMany(n => n.Cities)
.Where(c => c.Name.StartsWith("M"));
编辑:因为@Justin Niessner打败了我......也许是第二个where where
var result = nations.Where(n => n.Name == "UK")
.SelectMany(n => n.Cities.Where(c => c.Name.StartsWith("M"));