2012-09-06 162 views
11

我有一個項目的問題。我試圖獲得公司名單,但只是過濾那些位於「斯德哥爾摩」的公司。LINQ - 嵌套where子句

表結構

**Company**: 
CompanyID 
CompanyName 
etc… 

**CompanyAddressDetails** (relation table): 
Company_CompanyID 
CorrespondingAddress_AddressID 

**CorrespondingAddress**: 
AddressID 
StreetName 
City 
etc… 

現在我首先要做的是一個查詢:

var companyModel = from c in db.Company select c; 

它得到公司的完整列表,並且它們的相應地址(可以是多個),所以結果是這樣的:

enter image description here

所以我的問題是:我如何過濾取決於CorrespondingAddress下的一個元素是什麼?城市例如?

到目前爲止,我試過

companyModel = companyModel.Where(s => s.CorrespondingAddress.Where(x => x.City.Equals("Stockholm"))); 
companyModel = companyModel.Where(s => s.CorrespondingAddress.ToList().First().Address.Equals("Stockholm")); 

但他們沒有工作。謝謝!

回答

30
companyModel = companyModel 
       .Where(s => s.CorrespondingAddress 
        .Any(x => x.City.Equals("Stockholm"))); 
+0

+1應該這樣做 – Habib

+0

最優秀的! – BigOmega

4

老命()

companyModel = companyModel.Where(s => s.CorrespondingAddress.Any(x => x.City.Equals("Stockholm")));