【问题标题】:Linq - where clause on child objectLinq - 子对象的 where 子句
【发布时间】:2011-07-20 21:44:24
【问题描述】:

给定以下类:

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&lt;Nation&gt; 对象。

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

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

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您将执行以下操作:

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

    【讨论】:

      【解决方案2】:

      像这样:

      from n in Nation
      where n.Name == "UK"
      from c in n.Cities
      where c.Name.StartsWith("M")
      select c
      

      【讨论】:

        【解决方案3】:
        var result = nations.Where(n => n.Name == "UK")
                            .SelectMany(n => n.Cities)
                            .Where(c => c.Name.StartsWith("M"));
        

        编辑:因为@Justin Niessner 打败了我……也许会嵌套第二个 where 子句

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 2018-03-10
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多