Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - nested where clause

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!

like image 559
Johan Svensson Avatar asked Sep 06 '12 10:09

Johan Svensson


Video Answer


1 Answers

companyModel = companyModel
               .Where(s => s.CorrespondingAddress
                     .Any(x => x.City.Equals("Stockholm")));
like image 169
Raphaël Althaus Avatar answered Oct 13 '22 05:10

Raphaël Althaus