本文介绍了有条件"排序依据"在LINQ排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在LINQ,是有可能有有条件的排序依据排序顺序(升序与降序)。

像这样的东西(不适code):

 布尔标志;

(从ω在Widget中
 其中,w.Name.Contains(XYZ)
 排序依据w.Id(标志升序:降序)
 选择W)
 

解决方案

如果你建立的前pression增量就可以做到这一点。通常更容易使用EX pressions而不是COM prehension EX pressions:

 变种X = widgets.Where(W => w.Name.Contains(XYZ));
如果(旗){
  X = x.OrderBy(W => w.property);
} 其他 {
  X = x.OrderByDescending(W => w.property);
}
 

(假设Widget的属性几分,因为你没有列出一个依据。)

In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).

Something like this (not valid code):

bool flag;

(from w in widgets
 where w.Name.Contains("xyz")
 orderby w.Id (flag ? ascending : descending)
 select w)
解决方案

If you build the expression incrementally you can do this. Generally easier using expressions rather than comprehension expressions:

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

(Assuming the Widget's property is basis of sort since you don't list one.)

这篇关于有条件"排序依据"在LINQ排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:11