In LINQ, is it possible to have conditional orderby sort order (ascending vs. descending).
Something like this (not valid code):
bool flag;
(from w
You could try something like the following:
var q = from i in list
where i.Name = "name"
select i;
if(foo)
q = q.OrderBy(o=>o.Name);
else
q = q.OrderByDescending(o=>o.Name);
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));
...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;