Linq sorting with multiple column names in c#
I want to sort multiple columns with Linq
I used this link for reference, which is used for sorting of single column
by column name.
I am trying to use this method for sorting of multiple columns with column
names.
Here is what i am doing so far
public static IQueryable OrderByMultipleFields(this IQueryable q,
Dictionary fieldsToSort) {
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, fieldsToSort.First().Key);
var exp = Expression.Lambda(prop, param);
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
string method=string.Empty;
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = q.Expression;
int count = 0;
foreach (var fieldName in fieldsToSort)
{
method = fieldName.Value ? methodAsc : methodDesc;
prop = Expression.Property(param, fieldName.Key);
exp = Expression.Lambda(prop, param);
types = new Type[] { q.ElementType, exp.Body.Type };
if (count == 0)
{
mce = Expression.Call(typeof(Queryable), method, types,
q.Expression, exp);
}
else {
mce = Expression.Add(mce,
Expression.Call(typeof(Queryable), method, types,
q.Expression, exp));
}
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
count++;
}
return q.Provider.CreateQuery<T>(mce);
}
I am getting following error -
The binary operator Add is not defined for the types
'System.Linq.IOrderedQueryable1[SortDemo.Data.User]' and
'System.Linq.IOrderedQueryable1[SortDemo.Data.User]'.
what is the proper way to achieve this or is there any alternate approach
or method for this. thanks.
No comments:
Post a Comment