开发者

how to add sort direction with linq for sql?

开发者 https://www.devze.com 2022-12-10 23:11 出处:网络
Suppose I have linq expression q, then I want to add a sort to this query: q = q.OrderBy(p => p.Total);

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 开发者_StackOverflowdesc/asc option for SQL, how to add it in above linq expression?


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消