19

Possible Duplicates:
Linq to Entities - Sql “IN” clause
How to implement SQL “in” in Entity framework 4.0

how can I add WHERE IN statement like...

SELECT * FROM myTable WHERE ID IN (1,2,3,4,5)

in entity framework

Community
  • 1
  • 1
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191

2 Answers2

75

Use Contains:

int[] ids = { 1, 2, 3, 4, 5};

var query = db.myTable.Where(item => ids.Contains(item.ID));

or in query syntax:

int[] ids = { 1, 2, 3, 4, 5};

var query = from item in db.myTable
            where ids.Contains(item.ID)
            select item;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Jon Skeet thanks. But I have question. I believe you can solve that. That is when ids is being fetching from another table schema and contains some millions data then I can not make this faster. It is being slower for comparison. Is it my thinking or the compiler is giving best optimize run time by managing internal indexing/some other complex algorithm? Please response , I need it now. – Muhammad Ashikuzzaman Feb 28 '16 at 13:31
  • 2
    @MuhammadAshikuzzaman: In that case you should be doing it with a join instead. – Jon Skeet Feb 28 '16 at 13:32
  • Another thing is that if ids is another model list then I can not use .Contains function what is the way to check .Contains in lambda expression? thanks :) – Muhammad Ashikuzzaman Feb 28 '16 at 15:11
  • @MuhammadAshikuzzaman: At this point you should really be asking another question with all the relevant details. (Again, that sounds like you should be using a join...) – Jon Skeet Feb 28 '16 at 17:18
  • Thanks. Here I have make a question. Please see. [.Contains Problem](http://goo.gl/9bc7JF) – Muhammad Ashikuzzaman Feb 29 '16 at 05:52
3

I think answer lies somewhere along these lines...

Array a = {1,2,3,4,5}

...WHERE a.Contains(ID)
Peter Perháč
  • 20,434
  • 21
  • 120
  • 152