Linq - where clause on child

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; } } 

Suppose Nation is the aggregate root, and so I only have NationRepository , not a CityRepository (so Nation is the starting point for Linq queries). To clarify, the starting point will be an IQueryable<Nation> object.

How to write a query that returns a collection of City objects according to the following logic:

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

+6
source share
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")); 
+13
source

Like this:

 from n in Nation where n.Name == "UK" from c in n.Cities where c.Name.StartsWith("M") select c 
+8
source
 var result = nations.Where(n => n.Name == "UK") .SelectMany(n => n.Cities) .Where(c => c.Name.StartsWith("M")); 

EDIT: Because @Justin Niessner beat me ... maybe nest two is where the sentence

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

Source: https://habr.com/ru/post/893165/


All Articles