Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional "orderby" sort order in LINQ

Tags:

c#

.net

linq

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) 
like image 708
xyz Avatar asked Oct 22 '09 10:10

xyz


People also ask

How to sort in descending order in LINQ?

If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

How do I use ascending order in Linq?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

What is OrderByDescending?

OrderByDescending sorts the collection in descending order. OrderByDescending is valid only with the Method syntax. It is not valid in query syntax because the query syntax uses ascending and descending attributes as shown above.


2 Answers

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

like image 64
Richard Avatar answered Sep 27 '22 18:09

Richard


...Or do it all in one statement

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; 
like image 24
Carter Medlin Avatar answered Sep 27 '22 17:09

Carter Medlin