title: List of Expression<Func<T, TProperty>>
body: <p>I'm searching a way to store a collection of <code>Expression&lt;Func&lt;T, TProperty&gt;&gt;</code> used to order elements, and then to execute the stored list against a <code>IQueryable&lt;T&gt;</code> object (the underlying provider is Entity Framework).  </p>
  
  <p>For example, I would like to do something like this (<strong>this is pseudo code</strong>):</p>
  
  <pre><code>public class Program
  {
      public static void Main(string[] args)
      {
          OrderClause&lt;User&gt; orderBys = new OrderClause&lt;User&gt;();
          orderBys.AddOrderBy(u =&gt; u.Firstname);
          orderBys.AddOrderBy(u =&gt; u.Lastname);
          orderBys.AddOrderBy(u =&gt; u.Age);
  
          Repository&lt;User&gt; userRepository = new Repository&lt;User&gt;();
          IEnumerable&lt;User&gt; result = userRepository.Query(orderBys.OrderByClauses);
      }
  }
  </code></pre>
  
  <p>An order by clause (property on which to order):</p>
  
  <pre><code>public class OrderClause&lt;T&gt;
  {
      public void AddOrderBy&lt;TProperty&gt;(Expression&lt;Func&lt;T, TProperty&gt;&gt; orderBySelector)
      {
          _list.Add(orderBySelector);
      }
  
      public IEnumerable&lt;Expression&lt;Func&lt;T, ???&gt;&gt;&gt; OrderByClauses
      {
          get { return _list; }
      }
  }
  </code></pre>
  
  <p>A repository with my query method:</p>
  
  <pre><code>public class Repository&lt;T&gt;
  {
      public IEnumerable&lt;T&gt; Query(IEnumerable&lt;OrderClause&lt;T&gt;&gt; clauses)
      {
          foreach (OrderClause&lt;T, ???&gt; clause in clauses)
          {
              _query = _query.OrderBy(clause);
          }
  
          return _query.ToList();
      }
  }
  </code></pre>
  
  <p>My first idea was to convert the <code>Expression&lt;Func&lt;T, TProperty&gt;&gt;</code> into a string (the property name on which to sort). So basically, instead of storing a typed list (which is not possible because the TProperty is not constant), I store a list of string with the properties to sort on.</p>
  
  <p>But this doesn't work because then I cannot reconstruct the <code>Expression</code> back (I need it because IQueryable.OrderBy takes a <code>Expression&lt;Func&lt;T, TKey&gt;&gt;</code> as parameter). </p>
  
  <p>I also tried to dynamically create the Expression (with the help of Expression.Convert), to have a <code>Expression&lt;Func&lt;T, object&gt;&gt;</code> but then I got an exception from entity framework that said that it was not able to handle the Expression.Convert statement.</p>
  
  <p>If possible, I do not want to use an external library like the <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="noreferrer">Dynamic Linq Library</a>.</p>