Possible duplicate:
Dynamic LINQ OrderBy
I have a list of custom sorting options that are passed to the server using client-side network management (KendoUI grid, if you're interested). These sorting options have the ability to sort 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); } }
It works great, but it seems so ugly. How can I do this with reflection, so that I don’t need to write a custom function for each type of entity with which I want to do this? It would be nice if I could have only one function that did this no matter what the entity is.
source share