SharpAffair
SharpAffair

Reputation: 5478

Linq to SQL - match list to another list

I have a table Companies. And another table CompanyTypes.

One company can have multiple types.

I want to search companies with a select list of types (loaded into a list of strings).

If Company had only one type, I would do as follows:

Where searchTypes.Contains(Company.Type)

But how I execute a more complex query to get companies with desired types in another table?

Upvotes: 0

Views: 611

Answers (1)

mayabelle
mayabelle

Reputation: 10014

Try this (where you get CompanyTypes and Companies from your data):

IEnumerable<string> companyTypes = data.CompanyTypes; // filter this as needed
IEnumerable<Company> companiesOfType = data.Companies.Where(c => c.Types.Any(t => companyTypes.Contains(t)));

This will get you all companies that have at least one of the filtered company types. If you want all companies that have all the filtered company types, you can do this instead:

IEnumerable<string> companyTypes = data.CompanyTypes; // filter this as needed
IEnumerable<Company> companiesOfType = data.Companies.Where(c => c.Types.All(t => companyTypes.Contains(t)));

Upvotes: 1

Related Questions