views:

57

answers:

2

Suppose I have linq expression q, then I want to add a sort to this query:

q = q.OrderBy(p => p.Total);

but for sort, there is desc/asc option for SQL, how to add it in above linq expression?

+4  A: 

There's another method for that, OrderByDescending

A bit of an overkill, probably, but if you really want to be able to pass a parameter indicating sort order, you could create an extension method:

public static IOrderedEnumerable<TResult> OrderBy<TResult,TKey>(this IEnumerable<TResult> source, Func<TResult, TKey> keySelector, bool ascending)
{
   Func<Func<TResult, TKey>, IOrderedEnumerable<TResult>> orderMethod = source.OrderBy;

   if(!ascending)
      orderMethod = source.OrderByDescending;

   return orderMethod.Invoke(keySelector);
}

That way you'd be able to do

bool ascending = true;
list.OrderBy(item => item.Name, ascending);
David Hedlund
+3  A: 

OrderBy will sort by ascending order, for descending, use OrderByDescending:

q = q.OrderByDescending(p => p.Total);

And if you want to order by multiple columns, use the ThenBy, and ThenByDescending methods.

q = q.OrderBy(p => p.Col1).ThenByDescending(p => p.Col2);
CMS