C# – Dynamic “WHERE IN” on IQueryable (linq to SQL)

clambdalinq-to-sql

I have a LINQ to SQL query returning rows from a table into an IQueryable object.

IQueryable<MyClass> items = from table in DBContext.MyTable
select new MyClass
{
 ID = table.ID,
 Col1 = table.Col1,
 Col2 = table.Col2
}

I then want to perform a SQL "WHERE … IN …." query on the results. This works fine using the following. (return results with id's ID1 ID2 or ID3)

sQuery = "ID1,ID2,ID3";
string[] aSearch = sQuery.Split(',');
items = items.Where(i => aSearch.Contains(i.ID));

What I would like to be able to do, is perform the same operation, but not have to specify the i.ID part. So if I have the string of the field name I want to apply the "WHERE IN" clause to, how can I use this in the .Contains() method?

Best Answer

There's a couple of ways to do this. One way is to use Dynamic Linq. Another way is to use Predicate Builder.