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)
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)
...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;
Can also roll up Richard's answer into a convenient helper method, like so:
internal static class LinqExtensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool ascending)
{
return ascending ? source.OrderBy(keySelector)
: source.OrderByDescending(keySelector);
}
public static IOrderedEnumerable<TSource> ThenBy<TSource,TKey>
(this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool ascending)
{
return ascending ? source.ThenBy(keySelector)
: source.ThenByDescending(keySelector);
}
}