Does LINQ to SQL support the t-sql "in" statement

1.1k views Asked by At

I dont't know how to describe the title better (so feel free to change) but essntial I want to produce the equivilent of the following statement in LINQ to SQL:

select * from products where category in ('shoes','boots')

The fields will be coming from the query string essentially (more secure than this but for ease of explanation) i.e

string[] myfields = request.querystring["categories"].split(',');

Thanks

3

There are 3 answers

0
Jon Skeet On BEST ANSWER

Yes, you use Contains:

db.Products.Where(product => myFields.Contains(product.Category))

aka

from product in db.Products
where myFields.Contains(product.Category)
select product
0
David On

In theory you would use contains:

var productList = from product in context.Products
    where myfields.contains(product.category)
    select product

However you'll need to test this - I seem to recall there being a bug in the Linq2Sql optimizer when trying to deal with List<> and array values being used like this (it may have only occured if you tried to cast them as IQueryable)

0
Joel Martinez On

As other have mentioned, yes it does using the .Contains method. To benefit the other random people that may arrive here via Bing (or any of the other search engines): Linq-To-Entities does not support the .Contains method in the current version. However, with a simple extension method, you can do so:
http://george.tsiokos.com/posts/2007/11/30/linq-where-x-in/