In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).
Something like this (not valid code):
bool flag;
(from w
If the ordering property Id
is a number (or supports the unary minus) one could also do:
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 ...
You can even do more complex ordering and still keep it short:
var dict = new Dictionary<int, string>() { [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);
You can define a base query without the ordering, then order according to the flag:
var query=(from w in widgets
where w.Name.Contains("xyz")
select w);
var result = flag ?
query.OrderBy(w =>w) :
query.OrderByDescending(w = w);
bool flag;
from w in widgets
where w.Name.Contains("xyz")
orderby flag == true ? w.Id : w.Id descending
select w
ascending is impled
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.)
The MoreLINQ NuGet package also provides extension methods to make this more convenient. It also provides many more helpful extension methods and is therefore a stable go-to in my projects.