Possible Duplicate:
Dynamic LINQ OrderBy
I have a list of custom sort options that are passed to the server from a client-side grid control (KendoUI grid if you're wondering). These sort options have the property to sort by as a string. I wrote a switch method that will check the values of the sort object and apply the appropriate LINQ.
private IQueryable<Report> SortReports(IQueryable<Report> reports, KendoSort sort)
{
switch (sort.Field)
{
case "name":
return sort.Dir == "asc" ? reports.OrderBy(x => x.Name) : reports.OrderByDescending(x => x.Name);
case "description":
return sort.Dir == "asc" ? reports.OrderBy(x => x.Description) : reports.OrderByDescending(x => x.Description);
default:
return sort.Dir == "asc" ? reports.OrderBy(x => x.Id) : reports.OrderByDescending(x => x.Id);
}
}
This is working fine but seems so ugly. How might I do this with reflection so that I don't have to write a custom function for every type of entity I want to do this with? It would be nice if I could just have a single function that did this no matter what the entity.