给定以下类别:

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的名称为'UK'的所有Nation实例吗?

最佳答案

您将执行以下操作:

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

关于c# - Linq-子对象的where子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6762828/

10-11 05:23