I have the controller that sends me data from the database. Currently I am using switch() statement to do sorting logic and my code looks like this
switch (sort)
{
case "title":
books = books.OrderBy(b => b.Title);
break;
case "novelti_asc":
books = books.OrderBy(b => b.Date);
break;
case "novelti_des":
books = books.OrderByDescending(b => b.Date);
break;
default:
books = books.OrderBy(b => b.Title);
break;
}
This feels to me like an unnecessary code nesting. So I would like to know what is optimal solution for implementing data sorting.
>Solution :
I would use a Dictionary<string, Func<IQueryable<Book>, IQueryable<Book>>> like this:
var orderBy = new Dictionary<string, Func<IQueryable<Book>, IQueryable<Book>>>()
{
{ "title", bs => bs.OrderBy(b => b.Title) },
{ "novelti_asc", bs => bs.OrderBy(b => b.Date) },
{ "novelti_des", bs => bs.OrderByDescending(b => b.Date) },
};
And then write:
books = orderBy[orderBy.ContainsKey(sort) ? sort : "title"](books);
The advantage here is that you can extend the functionality at run-time. You simply add more elements to the dictionary. You perhaps might give different users different options.