title: Dynamic Order By in Linq
body: <p>I have an app that accesses database and has to order results by different fields depending on the input.</p>
  
  <p>Here is my function for sorting:</p>
  
  <pre><code>IQueryable&lt;Entity&gt; GetSortedData(IQueryable&lt;Entity&gt; result, String orderby, bool desc)
  {
     switch (orderby.ToLower())
     {
       case "id":
         result = result.OrderBy(c =&gt; c.Id);
         break;
  
       case "code":
         result = result.OrderBy(c =&gt; c.Code);
         break;
  
       case "active":
         result = result.OrderBy(c =&gt; c.Active);
         break;
  
       default:
         result = result.OrderBy(c =&gt; c.Name);
         break;
     }
  
     if (pageData.SortDesc)
     {
       var res = result.ToList();
       res.Reverse();
       return res.AsQueryable();
     }
  
     return result;      
  }
  </code></pre>
  
  <p>There are some problems with this code that I don't like:</p>
  
  <ol>
  <li><p>Too much repetitive code. If it was "pure <code>SQL</code>" query, it would look like</p>
  
  <p>SELECT * FROM data_table 
    ORDER BY 
     CASE @OrderBy 
       WHEN 'id' THEN id 
       WHEN 'code' THEN code<br>
       WHEN 'active' THEN active 
       ELSE name<br>
     END
  ;</p></li>
  <li><p>Conversion to list and back for reversing. I can not change return type and I definitely do not want to write even more useless code (essentially doubling <code>switch</code> <code>case</code> with <code>OrderByDescending</code>).</p></li>
  </ol>
  
  <p>Can anyone suggest ways of making this function better-looking, preferably still using <code>LINQ</code>?</p>