Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - where clause on child object

Tags:

c#

linq

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 have 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'?

like image 423
David Avatar asked Jul 20 '11 13:07

David


3 Answers

You would do the following:

var results = NationRepository.Where(n => n.Name == "UK")
                              .SelectMany(n => n.Cities)
                              .Where(c => c.Name.StartsWith("M"));
like image 112
Justin Niessner Avatar answered Oct 21 '22 06:10

Justin Niessner


Like this:

from n in Nation
where n.Name == "UK"
from c in n.Cities
where c.Name.StartsWith("M")
select c
like image 36
SLaks Avatar answered Oct 21 '22 05:10

SLaks


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"));
like image 26
NinjaNye Avatar answered Oct 21 '22 05:10

NinjaNye