开发者

Linq - where clause on child object

开发者 https://www.devze.com 2023-03-21 11:51 出处:网络
Given the following classes: public class Nation { public string Name { get; set; } public IEnumerable<City> Cities { get; private set; }

Given the following classes:

public class Nation
{
  public string Name { get; set; }
  public IEnumerable<City> Cities { get; private set; }
}

public class City
{
  public string Name { get; set; }
}

Assume Nation is the aggregate root and so I only ha开发者_StackOverflow社区ve a NationRepository and not a CityRepository (thus Nation is the starting point for Linq queries). To clarify, my starting point would be an IQueryable<Nation> object.

How would I write a query which returns a collection of City objects according to the following logic:

Select all City instances whose Name begins with 'M' whose parent Nation's name is 'UK'?


You would do the following:

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


Like this:

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

EDIT: Since @Justin Niessner beat me... maybe nest the second where clause

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

精彩评论

暂无评论...
验证码 换一张
取 消