Ye Peng Ye Peng - 5 months ago 36
SQL Question

How to implement Linq Where In query with an array

Can we build a Linq where clause really like SQL In? Like:

int[] ids = { 1, 2, 3, 4, 5};
var query = from item in db.myTable
where item.ID In ids
select item;


I know we can use a Contains keyword like below but I want to split the where clause without that local array ids so that I can save the where clause in a table to reuse it. I will save the real data { 1, 2, 3, 4, 5} in DB but not a local variable.

int[] ids = { 1, 2, 3, 4, 5};
var query = from item in db.myTable
where ids.Contains(item.ID)
select item;

Answer

The query should follow a similar pattern, you'll just pull the values from the other table instead of having them in an array.

var ids = db.someTable.Where(...).Select(e => e.ID);
var query = from item in db.myTable
        where ids.Contains(item.ID)
        select item;