假设我有 linq 表达式 q,然后我想为这个查询添加一个排序:
q = q.OrderBy(p => p.Total);
但是对于排序,SQL有desc/asc选项,如何在上面的linq表达式中添加?
最佳答案
还有另一种方法,OrderByDescending
可能有点矫枉过正,但如果您真的希望能够传递一个指示排序顺序的参数,您可以创建一个扩展方法:
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);
}
这样你就可以做到
bool ascending = true;
list.OrderBy(item => item.Name, ascending);
关于.net - 如何使用 linq for sql 添加排序方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1716494/