Conditional "orderby" sort order in LINQ
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;
Here is a more general solution, that can be used for various conditional lambda expressions without breaking the flow of the expression.
public static IEnumerable<T> IfThenElse<T>(
this IEnumerable<T> elements,
Func<bool> condition,
Func<IEnumerable<T>, IEnumerable<T>> thenPath,
Func<IEnumerable<T>, IEnumerable<T>> elsePath)
{
return condition()
? thenPath(elements)
: elsePath(elements);
}
e.g.
var result = widgets
.Where(w => w.Name.Contains("xyz"))
.IfThenElse(
() => flag,
e => e.OrderBy(w => w.Id),
e => e.OrderByDescending(w => w.Id));