Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Sort Direction From String

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;
}
like image 268
zzz Avatar asked Sep 29 '09 15:09

zzz


1 Answers

Ideally, you want to use OrderByDescending - you could of course cheat:

public static class MyExtensionMethods 
{
    public static IOrderedQueryable<TSource> OrderBy<TSource,TValue>(
        this IQueryable<TSource> source,
        Expression<Func<TSource,TValue>> selector,
        bool asc) 
    {
        return asc ? source.OrderBy(selector) : source.OrderByDescending(selector); 
    }
}

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).

like image 51
Marc Gravell Avatar answered Nov 14 '22 21:11

Marc Gravell