cool breeze
cool breeze

Reputation: 4811

How to check if a name is contained in another collection

I am doing something like this currently:

allSales.Where(x => x.location == "NorthAmerica" && x.CompanyName);

I have a List<Company> and the Company object has a .CompanyName property.

I want to filter for sales that have a CompanyName that are in the List collection.

The Company class has the following properties:

Company
Id
Name

The below doesn't work but it is what I want:

allSales.Where(x => x.location == "NorthAmerica" && 
       companies.Exists(x => x.Name = x.CompanyName));

where companies is List

Upvotes: 0

Views: 111

Answers (2)

Yacoub Massad
Yacoub Massad

Reputation: 27861

Assuming you have a List<Company> in a variable companies, you can use LINQ Any method to do something like this:

allSales
.Where(x =>
    x.location == "NorthAmerica" &&
    companies.Any(c => c.Name == x.CompanyName));

Upvotes: 4

James
James

Reputation: 1058

You can use the Any() method on your List<Company> object with a query to return true or false to your predicate. Try something like:

allSales.Where(x => x.location == "NorthAmerica" && companies.Any(c => c.Name == x.CompanyName);

Upvotes: 3

Related Questions