Linq - 子对象的where子句

时间:2011-07-20 13:34:48

标签: 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; }
}

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

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

选择City以“M”开头的所有Name个实例,其父级Nation的名称为“英国”?

3 个答案:

答案 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"));
相关问题