title: Get dynamic OrderBy in LINQ
body: <p>I am using datatables in quite a few pages in my ASP.NET MVC 3 site. They use server side paging and now I want to implement sorting based on the column headers. Datatables comes with <code>iSortCol_0</code>  which is an int value of what column is clicked.</p>
  
  <p>I did not like this approach as the query would end up something like:</p>
  
  <pre><code>if(iSortCol_0 == 0)
  {    
      // query
      // OderBy(x =&gt; x.CarName)
  }
  </code></pre>
  
  <p>Then this would be repeated for each column (plus an else clause on each to order by descending). So I have changed my approach and now pass the column name to the server.</p>
  
  <p>I have come up with the following:</p>
  
  <pre><code>Expression&lt;Func&lt;vw_Car, string&gt;&gt; sortExpression1 = null;
  Expression&lt;Func&lt;vw_Car, int&gt;&gt; sortExpression2 = null;
  
  switch(columnToSort) 
  {
      case "InvoiceNo": sortExpression1 = x =&gt; x.CarNo; break;
      case "ClientNumber": sortExpression1 = x =&gt; x.ForeName; break;
      case "ClientName": sortExpression1 = x =&gt; x.SurName; break;
      default: sortExpression2 =  x =&gt; x.Age.Value; break;
  }
  
  // start of query
  .OrderByDir(sortDirection, sortExpression1 , sortExpression2)
  </code></pre>
  
  <p>Now the <code>OrderByDir</code> looks like below:</p>
  
  <pre><code>public static IOrderedQueryable&lt;T&gt; OrderByDir&lt;T&gt;(this IQueryable&lt;T&gt; source, string dir, Expression&lt;Func&lt;T, string&gt;&gt; column1, Expression&lt;Func&lt;T, int&gt;&gt; column2)
  {
      if (column1 != null)
      {
          return dir == "asc" ? source.OrderBy(column1) : source.OrderByDescending(column1);
      }         
      if (column2 != null)
      {
          return dir == "asc" ? source.OrderBy(column2) : source.OrderByDescending(column2);
      }    
      return null;
  }
  </code></pre>
  
  <p>This works in that it sorts columns that are of type <code>string</code> or <code>int</code>. I have another column of <code>DateTime</code> that I want to sort, so I would need to write another <code>sortExpression3</code> and then add that to my <code>OrderByDir</code>.</p>
  
  <p>However I don't really like the implementation - I had attempted to write a generic sort expression that took an object as second parameter instead of <code>string</code>, <code>int</code>, <code>Datetime</code>, but when had this code in place, I was getting <em>Unable to cast the type 'System.DateTime' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types</em>.</p>
  
  <p>Any one any ideas as to a possible better approach to this?</p>