views:

309

answers:

2

Bear with me, I'm beginning: How can I select multiple elements using a WHERE...IN... type of clause as in

select * from orders where orderid in (1, 4, 5)

in LinqToSql? I'd prefer not to have a lambda expression since they scare me. Thanks in advance!

+11  A: 

LINQ has "Contains" which is like "IN" but expressed the other way round - an element isn't "in" a set, a set "contains" an element.

int[] validIds = { 1, 4, 5 };
var query = from order in db.Orders
            where validIds.Contains(order.Id)
            select order

This is more simply expressed (IMO) with a lambda though:

int[] validIds = { 1, 4, 5 };
var query = db.Orders.Where(order => validIds.Contains(order.Id));

I realise lambdas are "new" and therefore scary to some extent, but it's really well worth grabbing hold of them with both hands. They're lovely.

Jon Skeet
you're the man jon, seriously. thanks for your answer.
Matthias
Ooops... I completely forgot about the Contain extension method in my answer...
James Curran
A: 
int[] arry = new int[] {1,4,5};

var q = from r in orders
        where Array.IndexOf(array, orderid) != -1
        select r;

or

List<int> lst = new List<int>(new int[] {1,4,5});
var q = from r in orders
        where lst.Contains(orderid);
        select r;
James Curran
uh, I guess I still have a problem here: I get an exception when trying to run with a foreach over the resultset. unfortunately I do only have a german exception text for it, but it says something like that the expression "Int32 IndexOf[Int32](Int32[], Int32)" can't be recognized.
Matthias
LINQ to SQL doesn't know about IndexOf, but does know about Contains.
Jon Skeet