LINQ - nested where clause

c# entity-framework linq

Question

I have a problem with a project. I’m trying to get a list of companies, but only filter those companies that are located in “Stockholm”.

Table structure

**Company**:
CompanyID
CompanyName
etc…

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

**CorrespondingAddress**:
AddressID
StreetName
City
etc…

Now what I first do is a query:

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

Which gets the full list of companies and having their Corresponding Addresses (which can be multiple), so the results looks like this:

enter image description here

So my question is: how can I filter depending on what one of the nestled elements under CorrespondingAddress is? City for example?

So far I tried

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

But none of them works. Thanks!

1
13
9/6/2012 10:18:32 AM

Accepted Answer

companyModel = companyModel
               .Where(s => s.CorrespondingAddress
                     .Any(x => x.City.Equals("Stockholm")));
51
9/6/2012 10:15:00 AM

Popular Answer

Try Any()

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow