2011-07-20 50 views
6

考慮以下類:LINQ的 - 在子對象上從句

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<Nation>對象。

我將如何編寫一個查詢根據以下邏輯City對象的集合返回:

選擇所有City情況下,其Name開始其母公司Nation的名字是‘UK’「M」?

回答

13

你會做到以下幾點:

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

像這樣:

from n in Nation 
where n.Name == "UK" 
from c in n.Cities 
where c.Name.StartsWith("M") 
select c 
2
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"));