title: Strongly typed dynamic Linq sorting
body: <p>I'm trying to build some code for dynamically sorting a Linq IQueryable&lt;>.</p>
  
  <p>The obvious way is here, which sorts a list using a string for the field name<br>
  <a href="http://dvanderboom.wordpress.com/2008/12/19/dynamically-composing-linq-orderby-clauses/" rel="noreferrer">http://dvanderboom.wordpress.com/2008/12/19/dynamically-composing-linq-orderby-clauses/</a></p>
  
  <p>However I want one change - compile time checking of field names, and the ability to use refactoring/Find All References to support later maintenance. That means I want to define the fields as f=>f.Name, instead of as strings.</p>
  
  <p>For my specific use I want to encapsulate some code that would decide which of a list of named "OrderBy" expressions should be used based on user input, without writing different code every time.</p>
  
  <p>Here is the gist of what I've written:</p>
  
  <pre><code>var list = from m Movies select m; // Get our list
  
  var sorter = list.GetSorter(...); // Pass in some global user settings object
  
  sorter.AddSort("NAME", m=&gt;m.Name);
  sorter.AddSort("YEAR", m=&gt;m.Year).ThenBy(m=&gt;m.Year);
  
  list = sorter.GetSortedList();
  
  ...
  public class Sorter&lt;TSource&gt;
  ...
  public static Sorter&lt;TSource&gt; GetSorter(this IQueryable&lt;TSource&gt; source, ...)
  </code></pre>
  
  <p>The GetSortedList function determines which of the named sorts to use, which results in a List object, where each FieldData contains the MethodInfo and Type values of the fields passed in AddSort:</p>
  
  <pre><code>public SorterItem&lt;TSource&gt; AddSort(Func&lt;T, TKey&gt; field)
  {
     MethodInfo ... = field.Method;
     Type ... = TypeOf(TKey);
     // Create item, add item to diction, add fields to item's List&lt;&gt;
     // The item has the ThenBy method, which just adds another field to the List&lt;&gt;
  }
  </code></pre>
  
  <p>I'm not sure if there is a way to store the entire field object in a way that would allow it be returned later (it would be impossible to cast, since it is a generic type)</p>
  
  <p>Is there a way I could adapt the sample code, or come up with entirely new code, in order to sort using strongly typed field names <i>after</i> they have been stored in some container and retrieved (losing any generic type casting)</p>