Need a "WHERE field IN (x, y, z)" Clause with LINQ

A colleague and I were talking about some LINQ features yesterday and one of the topics that came up was how to implement an IN clause. Ya know, similar to how SQL statements can use an IN clause in the WHERE clause like this:

SELECT city FROM Customers WHERE state IN ('FL', 'NY'', 'NC')

Then I remembered Dan Wahlin's post on a similar topic where he shows the following solution (from Dan's post):

The code uses the Contains() method to search for a specific ProductID within the collection which ends up creating a WHERE IN type query.  You can do the same thing with LINQ:

public static Product[] GetProducts(Guid[] prodIDs)
return (from p in GetProducts()
where prodIDs.Contains(p.ProductID)
select p).ToArray<Product>();

The idea here is that the LINQ query is written normally (meaning the from and the select clauses reference the objects). Then the where clause in the LINQ query operates on an array of values. The array of values contains the values you would put in the IN clause. The array supports standard query operators so you can use the Contains method on the array and pass in the value you want to look for.

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders