子对象上的Linq-where子句

本文关键字:Linq-where 子句 对象 | 更新日期: 2023-09-27 18:02:58

给定以下类:

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对象集合的查询:

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

子对象上的Linq-where子句

您可以执行以下操作:

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

像这样:

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"));

编辑:既然@Justin Niessner打败了我……也许第二个嵌套在哪里子句

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