LINQ中的条件“orderby”排序顺序

在LINQ中,是否可以通过排序顺序(升序与降序)进行条件排序。

像这样的东西(不是有效的代码):

bool flag; (from w in widgets where w.Name.Contains("xyz") orderby w.Id (flag ? ascending : descending) select w) 

如果以增量方式构建表达式,则可以执行此操作。 通常更容易使用表达式而不是理解表达式:

 var x = widgets.Where(w => w.Name.Contains("xyz")); if (flag) { x = x.OrderBy(w => w.property); } else { x = x.OrderByDescending(w => w.property); } 

(假设Widget的property是sort的基础,因为你没有列出一个。)

……或者在一个声明中全部完成

 bool flag; var result = from w in widgets where w.Name.Contains("xyz") orderby flag ? w.Id : 0, flag ? 0 : w.Id descending select w; 

您可以定义没有排序的基本查询,然后根据标志排序:

 var query=(from w in widgets where w.Name.Contains("xyz") select w); var result = flag ? query.OrderBy(w =>w) : query.OrderByDescending(w = w); 

您可以尝试以下内容:

 var q = from i in list where i.Name = "name" select i; if(foo) q = q.OrderBy(o=>o.Name); else q = q.OrderByDescending(o=>o.Name); 

这是一个更通用的解决方案,可用于各种条件lambda表达式而不会破坏表达式的流程。

 public static IEnumerable IfThenElse( this IEnumerable elements, Func condition, Func, IEnumerable> thenPath, Func, IEnumerable> elsePath) { return condition() ? thenPath(elements) : elsePath(elements); } 

例如

 var result = widgets .Where(w => w.Name.Contains("xyz")) .IfThenElse( () => flag, e => e.OrderBy(w => w.Id), e => e.OrderByDescending(w => w.Id)); 

如果订购属性Id是一个数字(或支持一元减号),那么也可以:

 bool ascending = ... collection.Where(x => ...) .OrderBy(x => ascending ? x.Id : -x.Id) .Select(x => ...) // LINQ query from x in ... orderby (ascending ? x.Id : -x.Id) select ... 

MoreLINQ NuGet 包还提供了扩展方法,使这更方便。 它还提供了许多更有用的扩展方法,因此是我项目中的一个稳定的方法。

您甚至可以进行更复杂的订购并保持简短:

  var dict = new Dictionary() { [1] = "z", [3] = "b", [2] = "c" }; var condition = true; var result = (condition ? dict.OrderBy(x => x.Key) : dict.OrderByDescending(x => x.Value)) .Select(x => x.Value);