Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to realize tsql "IN" equivalent using dynamic Linq

I'm creating a generic form (C#) which can receive any Linq query. In this form I want to be able to add filters (WHERE clauses). For operators like '=', '>', 'Like', etc. I can do things like IQueryable.Where(someFieldname + "> @0", someCriteria). But when I want to be able to do the equivalent of a T-sql "IN" I am totally lost. I've searched hours, but cannot find a way to realize it.

When thinking about it a way that it should be possible is to put the values for the IN-clause in a string array or some other simple list of strings. Then join this list with the base query. But how can I join these two when base query can be any query?

Example: Say my base query is something like:

IQueryable<Object> q = from a in db.Adresses
                       select new { a.Street, a.HouseNr };

In the form I want to be able to filter on HouseNr like this: Where HouseNr IN (1, 3, 5) The numbers (1, 3, 5) are available in a string array (or any other List of strings).

How can I achieve this, knowing that the base query can be anything?

like image 583
Roland Deschain Avatar asked Jul 26 '11 15:07

Roland Deschain


1 Answers

int[] list = new[]{1, 3, 5};
IQueryable<Object> q = from a in db.Adresses
                       where list.Contains(a.HouseNr)
                       select new { a.Street, a.HouseNr };
like image 63
Bala R Avatar answered Oct 09 '22 02:10

Bala R