title: Need to cast a IQueryable<T> at runtime
body: <p>I have done my research but I am still unable to find a solution to this problem. I have a program that is using lambda expressions with linq to sql. I would like to instantiate the main linq object as an dynamic object and cast it in the rest of the program to different types base off a value specified. For instance:</p>
  
  <pre><code>int Value1 = 'Ob1';
  int Value2 = 'OB2';
  
  int Currentval = Value1;
  
  dynamic val;
  
  if (Currentval == Value1;
          val = (from c in datacontext.UniqueTable1
                 select c);
  else
          val = (from c in datacontext.UniqueTable2
                 select c);
  
  
  dynamic val1;
  
  if (Currentval == Value1)
  {
    val1 = ((IQueryable&lt;datacontex.UniqueTable1&gt;)val).Where(c =&gt; c.ID == 2);
  }
  else if (Currentval == Value1)
  {
    val1 = ((IQueryable&lt;datacontex.UniqueTable2&gt;val).Where(c =&gt; c.ID == 3);
  }
  </code></pre>
  
  <p>You cannot do what I am proposing above because the compiler complains about the Lambda expression. Can anyone help me out with this?</p>
  
  <p>Update:</p>
  
  <p>The error that I get when i change to dynamic is:</p>
  
  <p>Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type</p>
  
  <p>Update2:</p>
  
  <p>There is one other problem with this, I have alot of logic that makes use of the data selected from the lamda expressions that happen above. Things like:</p>
  
  <pre><code>if (val1.Where(c =&gt; c.ID == 3).Count() &gt; 0)
  {...}
  </code></pre>
  
  <p>I would like to cast these values based on the the type selected from <em>CurrentVal</em>. So I'm thinking some type of reflection would be needed. Setting it to <em>IQueryable</em> is along the same lines as setting it to <em>dynamic</em></p>
  
  <p>So what I am thinking is something like, but I am not sure something like this is possible.</p>
  
  <pre><code>if (((IQueryable&lt;CurrentVal&gt;)val1).Where(c =&gt; c.ID == 3).Count() &gt; 0)
  {...}
  </code></pre>