Accepted answer

after a lot of struggle i found solution to my question. i want to achieve this sql query

select * from courses where courseid in (1, 2, 3, 4)

using linq to entities, but i want to pass in(1,2,3,4) list dynamically to linq query. i created an extension class for that purpose.

public static class linqextensions
   public static expression<func<t, bool>> false<t>() { return f => false; } 
   public static expression<func<t, bool>> in<t, tvalue>(this expression<func<t, bool>> predicate,string propertyname, list<tvalue> values)
           var param = predicate.parameters.single();
           memberexpression property = expression.propertyorfield(param, propertyname);            
           var micontain = typeof(list<tvalue>).getmethod("contains");            
           var mc =, micontain, property);
           return expression.lambda<func<t, bool>>(mc, param);

use of linqextensions

var pred = linqextensions.false<course>(); //you can chain in function like  linqextensions.false<course>().in<course, int>("courseid", inlist);
var inlist= new list<int>(){1, 2, 3}; //keep in mind the list must be of same type of the property that will be compared with. in my case courseid is integer so the in list have integer values
pred<course, int>("courseid", inlist); //tvalue is int. as courseid is of type int.
var data =;

i hope this might be beneficial for some one


have you seen the type of

var courselist = => ids.contains(c.courseid)))

above statement would not return actual list of courses. the query is not executed yet. it just returns iquereable. the query is executed when you actually call .tolist() method on it

so, your solution is..

  1. create array of ids using for loop and then simply run the below query

  2. var courselist = => ids.contains(c.courseid))).tolist()

Related Query