I didn't think this would be so rare to find but as it seems, it is. Here's the situation.
I've a ApplySort method which takes in 3 parameters posted from a mvc page.
private List<dynamic> ApplySort(List<dynamic> 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 => a.name).ToList();
break;
case "assigned":
listToBeSorted = listToBeSorted.OrderByDescending(a => a.title).ToList();
break;
case "duedate":
listToBeSorted = listToBeSorted.OrderByDescending(a => a.end).ToList();
break;
case "status":
listToBeSorted = listToBeSorted.OrderByDescending(a => a.title).ToList();
break;
default:
listToBeSorted = listToBeSorted.OrderByDescending(a => a.title).ToList();
break;
}
}
else
{
// same code as in if-block, with just OrderBy calls instead of OrderByDescending
}
return listToBeSorted;
}
Two problems:
1) Method seems unnecessarily long (with very similar code inside if and else blocks).
2) I want to be able to sort using multiple columns. 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. I can use ThenBy by checking params sequentially. But how to dynamically apply a chain of ThenBy(s) based on the param value, where the number of ThenBy can vary.
string[] sortParams = sortBy.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
listToBeSorted.OrderBy(i=>i.sortParams[0]).ThenBy(j=>j.sortParams[1]).ThenBy(k=>k.sortParams[2])...(so on till sortParams.length)
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.