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