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'?
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With