Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select records that match a list of IDs

Is it possible to change my query below, so that it uses the types list within a contains type query.

So instead of having:

var cust = db.Customers.Where(x => x.type_id==9 || x.type_id==15 || x.type_id==16).ToList();

...I would have something like:

List<int> types = new List<int> { 9, 15, 16 };
var cust = db.Customers.Where(x => types.contains(x.type_id).ToList();

(type_id is not the primary key).

Thank you,

Mark

like image 819
Mark Avatar asked Apr 06 '14 19:04

Mark


1 Answers

Yes, method List<T>.Contains will be translated into SQL IN operator:

var cust = db.Customers.Where(x => types.Contains(x.type_id)).ToList();

Generated query will look like:

SELECT * FROM Customers
WHERE type_id IN (@p0, @p1, @p2)
like image 57
Sergey Berezovskiy Avatar answered Oct 01 '22 00:10

Sergey Berezovskiy