I have an api Get
method which accepts sort property as a string.
What is a best solution to handle it without using switch
statement?
public ActionResult Index(string sortOrder)
{
var students = from s in db.Students
select s;
switch (sortOrder)
{
case "LastName":
students = students.OrderByDescending(s => s.LastName);
break;
case "EnrollmentDate":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "Birthday":
students = students.OrderBy(s => s.Birthday);
break;
default:
students = students.OrderBy(s => s.LastName);
break;
}
return View(students.ToList());
}
Following code I found on microsoft's page, but I believe there is should be more elegant way to do it.