title: Combine OrderBy Expression with Where Expression
body: <p>I found the following question that can combine multiple <code>Expression&lt;Func&lt;T,bool&gt;&gt;</code> expressions:</p>
  
  <p><a href="https://stackoverflow.com/questions/1131869/how-to-merge-two-c-sharp-lamba-expressions-without-an-invoke">How to merge two C# Lambda Expressions without an invoke?</a></p>
  
  <p>I'm wondering whether, using a similar technique, how you go about merging a .OrderBy <code>Expression&lt;Func&lt;Entity, Key&gt;&gt;</code> with a .Where <code>Expression&lt;Func&lt;Entity, bool&gt;&gt;</code> into one Expression of type, or inheriting from type, <code>System.Linq.Expressions.Expression</code>.</p>
  
  <p>I'm making a really cut down QueryProvider-style class for taking <code>T =&gt; T == ...</code> Func's via public methods <code>.Where</code> and <code>.OrderBy</code>. This is with the intention that the expression this class builds gets passed to a QueryTranslator to create suitable SQL.</p>
  
  <p>A QueryTranslator of this style, when called from a QueryProvider, typically takes one <code>System.Linq.Expressions.Expression</code> as an argument which it then translates to SQL.  </p>
  
  <p>I can follow through and understand the question above for merging two <code>.Where</code> Funcs. The following blog post was particularly useful for this, and I traced through each of the examples:</p>
  
  <p><a href="http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx</a></p>
  
  <p>This CodeProject article was also useful:</p>
  
  <p><a href="http://www.codeproject.com/Articles/24255/Exploring-Lambda-Expression-in-C" rel="nofollow noreferrer">http://www.codeproject.com/Articles/24255/Exploring-Lambda-Expression-in-C</a></p>
  
  <p>When combining a .OrderBy Func with a .Where Func however the two have different generic arguments. In the case of the .Where it's a <code>Func&lt;Entity, bool&gt;</code>, and in the case of the .OrderBy it's a <code>Func&lt;Entity, Key&gt;</code>. </p>
  
  <p>Merging these two Expressions, on the surface, isn't as straight forward as merging two with the same generic arguments.  </p>
  
  <p>The in-built Func-Expression-producing-engine (unsure of exact term) is able to combine a .Where Func with a .OrderBy Func. I'm curious about what goes on under the hood when these two expressions are merged to become one <code>System.Linq.Expressions.Expression</code>.  Is it possible, and if so how would you go about combining an <code>Expression&lt;Func&lt;Entity, bool&gt;&gt;</code> with an <code>Expression&lt;Func&lt;Entity,Key&gt;&gt;</code> assuming the Entity is of the same type in each Expression?</p>