I am trying to sort a set of Users. I have access to the sorting property and direction (asc, desc). My current order by query is below. But as you can see it doesn't account for the sort direction. How do can I build this expression without having to use Dynamic Linq, or adding another set of statements for "asc" or "desc" sort direction.
public override IQueryable<DalLinq.User> GetSort(IQueryable<DalLinq.User> query)
{
//SelectArgs.SortDirection <- Sort Direction
switch (SelectArgs.SortProperty)
{
case "LastName":
query = query.OrderBy(p => p.LastName);
break;
case "FirstName":
query = query.OrderBy(p => p.FirstName);
break;
default:
query = query.OrderBy(p => p.UserName);
break;
}
return query;
}
Have a look at the CS Code Samples. There are a dynamic Linq examples.
From the samples:
Order by Code:
But be sure that you check User Input!
Ideally, you want to use
OrderByDescending
- you could of course cheat:And use
OrderBy
passing in the selector and a bool?If you don't need the static typing, you can also build the expressions dynamically from the ground up, of course - like this short sample (similar in nature to the dynamic LINQ library).
It'd be an if statement I think, no other simple way to do it, i.e.:
Have a look at this as well: Sorting a list using Lambda/Linq to objects