Selecting OrderBy or OrderByDescending using a delegate

Linq to SQL has two methods to sort a query ascending or descending, respectively:

  • OrderBy()
  • OrderByDescending()

Sometimes, you want to have a SortDirection determining the sort order. You can do this by using a delegate:

public delegate IOrderedEnumerable<TSource> OrderFunc<TSource, TKey>(Func<TSource, TKey> keySelector);


OrderFunc<Car, string> orderFunc;

if (sortDirection == SortDirection.Ascending)
    orderFunc = matches.OrderBy;
    orderFunc = matches.OrderByDescending;

result = orderFunc(c => c.Wheels);

OrderFunc is the type of a variable, just like int or string. The variable orderFunc is of type OrderFunc. Instead of holding a value, it holds a reference to a method. In our case, that method is either OrderBy or OrderByDescending.