score:2

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>();

score:1

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

http://blogs.sftsrc.com/stuart/archive/2009/02/19/130.aspx

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


Related Query

More Query from same tag