Accepted answer

You could use reflection, but that would be rather slow. The most efficient would be declare a delegate to use in the sort, and assign a function depending on the string:

Func<Employee,string> order;
switch (field) {
   case "FirstName": order = x => x.FristName;
   case "LastName": order = x => x.LastName;

For the direction I think it's best to simply use separate codes:

var list = _employeeService.List();
IEnumerable<employee> sorted;
if (direction == "ascending") {
   sorted = list.OrderBy(order);
} else {
   sorted = list.OrderByDescending(order);
_model.List = sorted.ToList<Employee>();


Search for sites that talk about dynamic LINQ expressions. For example, this one shows how to do dynamic sorting:

You can then also choose whether to call OrderBy or OrderByDescending depending on the direction parameter.

Related Query

More Query from same tag