c# dynamically picking the search direction with linq
by brian on Sep.30, 2008, under .NET, c#, linq, sql
I’ve recently been writing an application that builds a linq to sql query dynamically. For instance:
MyDataContext dc() = new MyDataContext; var query = dc.MyTables; query = query.Where( t=>t.id > 10);
and so I want to order it by a certain column:
query = query.OrderBy( t=>t.id )
but the problem is the order direction isn’t know before hand so at first I was stuck with the following:
if ( descending )
query = query.OrderByDescending( t=>t.id);
else
query = query.OrderBy(t=>t.id);
Now if there is only a few possible columns to sort against it isn’t too bad. But when you have 10 different possible columns it really makes a lot of extra work just to control to sort direction. So I made a little helper class that allows the following. It works with linq and linq to sql:
query = query.OrderByAscDec( t=>t.id, descending );
here’s the static class that implments the OrderByAscDec function:
static class VPLinqExtensions
{
public static IOrderedQueryable<TSource> OrderByAscDes<TSource, TKey>(
this IQueryable<TSource> source,
System.Linq.Expressions.Expression<Func<TSource,
TKey>> keySelector, bool IsDescending)
{
if (IsDescending)
return source.OrderByDescending(keySelector);
else
return source.OrderBy(keySelector);
}
}
