1:
2: public DataTable GetSomeData(par1, par2...., string sortExpression)
3: {
4: var query = (//Linq query goes here )
5: // We want something like this which is not possible as of now
6: var query = (some query) (OrderBy SortExpression)
7: }
8: public static Util
9: {
10: //Thanks to Ernesto for pointing out a small correction in method signature.
11: public static IQueryable<TEntity> OrderBy(this IQueryable<TEntity> source, string sortExpression) where TEntity : class
12: {
13: var type = typeof(TEntity);
14: // Remember that for ascending order GridView just returns the column name and for descending it returns column name followed by DESC keyword
15: // Therefore we need to examine the sortExpression and separate out Column Name and order (ASC/DESC)
16: string[] expressionParts = sortExpression.Split(' '); // Assuming sortExpression is like [ColoumnName DESC] or [ColumnName]
17: string orderByProperty = expressionParts[0];
18: string sortDirection = "ASC";
19: string methodName = "OrderBy";
20: //if sortDirection is descending
21: if (expressionParts.Length > 1 && expressionParts[1] == "DESC")
22: {
23: sortDirection = "Descending";
24: methodName += sortDirection; // Add sort direction at the end of Method name
25: }
26: var property = type.GetProperty(orderByProperty);
27: var parameter = Expression.Parameter(type, "p");
28: var propertyAccess = Expression.MakeMemberAccess(parameter, property);
29: var orderByExp = Expression.Lambda(propertyAccess, parameter);
30: MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName,
31: new Type[] { type, property.PropertyType },
32: source.Expression, Expression.Quote(orderByExp));
33: return source.Provider.CreateQuery(resultExp);
34: }
35: }