title: Programmatically chain OrderBy/ThenBy using LINQ / Entity Framework
body: <p>I have a reporting interface where the end user gets to select multiple fields for the sort order of the returned report.  The problem I am having is that I can't really chain the OrderBy / ThenBy methods, since I'm iterating through a list of sort fields. I'm thinking something like this:</p>
  
  <pre><code>foreach (string sort in data.SortParams)
  {
      switch (sort)
      {
          case "state":
              query = query.ThenBy(l =&gt; l.RegionCode);
              break;
          case "type":
              query = query.ThenBy(l =&gt; l.Type);
              break;
          case "color":
              query = query.ThenBy(l =&gt; l.Color);
              break;
          case "category":
              query = query.OrderBy(l =&gt; l.Category);
              break;
      }
  }
  </code></pre>
  
  <p>(Note: I've removed the switch determining if this is the first sort item for simplicity's sake.)</p>
  
  <p>Any thoughts on how to iterate through a collection to determine the sort order?</p>