tags:

views:

95

answers:

2

What is in and not in equals in LINQ to SQL?

For example

select * from table in ( ...)
and 
select * from table not in (..)

What is equal to the above statement in LINQ to SQL?

+3  A: 

You use, where <list>.Contains( <item> )

var myProducts = from p in db.Products
                 where productList.Contains(p.ProductID)
                 select p;

Or you can have a list predefined as such:

var ids = {1, 2, 3};

var query = from item in context.items
            where ids.Contains( item.id )
            select item;

For the 'NOT' case, just add the '!' operator before the 'Contains' statement.

j0rd4n
How do you handle if it's in a list? IN('a', 'b', 'c')
DOK
@DOK he just mentioned how you handle if it's in a list.
Randolpho
See my updated example.
j0rd4n
this only equal to in clause what is for not in
Pranay Rana
See my updated statement for the 'NOT' condition. Essentially, you just need to add '!' before the Contains call.
j0rd4n
+2  A: 

I'm confused by your question. in and not in operate on fields in the query, yet you're not specifying a field in your example query. So it should be something like:

select * from table where fieldname in ('val1', 'val2')

or

select * from table where fieldname not in (1, 2)

The equivalent of those queries in LINQ to SQL would be something like this:

List<string> validValues = new List<string>() { "val1", "val2"};
var qry = from item in dataContext.TableName
          where validValues.Contains(item.FieldName)
          select item;

and this:

List<int> validValues = new List<int>() { 1, 2};
var qry = from item in dataContext.TableName
          where !validValues.Contains(item.FieldName)
          select item;
Randolpho