Sam
Sam

Reputation: 30302

Making sure a value is equal to one of many in LINQ

I have an IEnumerable containing values like "ABC", "DEF", etc.

I'm trying to form a LINQ query where the value of a property in my object may be equal to one of the many values contained in my IEnumerable. How do I form that LINQ query?

var statesFilter = new List<string>();
statesFilter.Add("NY");
statesFilter.Add("CA");

var employees = new List<Employee>();
employees = getDataFromSomewhere();

// Code below is not working. Just wanted to give you an idea about my LINQ query
var myFilteredList = employees.Where(x => x.State.Contains(statesFilter));

Employee class could be something like this:

public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string State { get; set; }
}

Upvotes: 4

Views: 1604

Answers (2)

ocuenca
ocuenca

Reputation: 39366

If State property is of type string, you should change your Where to the following:

var myFilteredList = employees.Where(x => statesFilter.Contains(x.State));

Also, you can do this:

var myFilteredList = employees.Where(x => statesFilter.Any(s=>s==x.State));

Upvotes: 2

tede24
tede24

Reputation: 2354

Condition should be

x=>statesFilter.Contains(x.State))

Upvotes: 1

Related Questions