Search code examples
c#linqlinq-to-sqlsortingsortdirection

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;
}

Solution

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