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 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.
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.
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.
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.)
...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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With