Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top