Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting incoming data

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading