title: LINQ How to use multiple ThenBy dynamically?
body: <p>I didn't think this would be so rare to find but as it seems, it is. Here's the situation.</p>
  
  <p>I've a <strong>ApplySort</strong> method which takes in 3 parameters posted from a mvc page.</p>
  
  <pre><code>    private List&lt;dynamic&gt; ApplySort(List&lt;dynamic&gt; listToBeSorted, string sortBy, string sortOrder)
      {
          if (String.IsNullOrEmpty(sortBy))
              sortBy = "createddate";
          if (String.IsNullOrEmpty(sortOrder) || sortOrder.Trim() != "0")
              sortOrder = "1"; // 1 = descending, 0 = ascending
          if (sortOrder == "1")
          {
              switch (sortBy)
              {
                  case "name":
                      listToBeSorted = listToBeSorted.OrderByDescending(a =&gt; a.name).ToList();
                      break;
                  case "assigned":
                      listToBeSorted = listToBeSorted.OrderByDescending(a =&gt; a.title).ToList();
                      break;
                  case "duedate":
                      listToBeSorted = listToBeSorted.OrderByDescending(a =&gt; a.end).ToList();
                      break;
                  case "status":
                      listToBeSorted = listToBeSorted.OrderByDescending(a =&gt; a.title).ToList();
                      break;
                  default:
                      listToBeSorted = listToBeSorted.OrderByDescending(a =&gt; a.title).ToList();
                      break;
              }
          }
          else
          {
              // same code as in if-block, with just OrderBy calls instead of OrderByDescending
          }
          return listToBeSorted;
      }
  </code></pre>
  
  <p>Two problems: </p>
  
  <p>1) Method seems unnecessarily long (with very similar code inside if and else blocks).</p>
  
  <p>2) <strong>I want to be able to sort using multiple columns.</strong> sortBy param can have values like "name,title,createddate,status". So the sort applied should be, first by name, thenby title, then by createddate...and so on. <em>I can use <strong>ThenBy</strong> by checking params sequentially. <strong>But how to dynamically apply a chain of ThenBy</strong>(s) based on the param value, where the number of ThenBy can vary</em>.</p>
  
  <pre><code>string[] sortParams = sortBy.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
  listToBeSorted.OrderBy(i=&gt;i.sortParams[0]).ThenBy(j=&gt;j.sortParams[1]).ThenBy(k=&gt;k.sortParams[2])...(so on till sortParams.length)
  </code></pre>
  
  <p>How would I do this ? Plus, also how can I use the sortOrder parameter to sort by ascending or descending in the same line instead of using if-else.</p>