Reputation: 21184
Here is Generic Repository's way of storing an OrderBy:
private Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy;
Here's Microsoft's OrderBy that takes a string of field names (from Microsoft's Dynamic Linq):
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
string ordering, params object[] values);
Here's our Extension Method that translates our array of fields to a comma separated OrderBy/ThenBy:
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source,
ICollection<string> orderBy)
{
return source.OrderBy( String.Join(",", orderBy) );
}
All that works well but requires appending the OrderBy to the original Entity. How would we save the OrderBy in a variable to append to that Entity later?
//Something like
Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = ??
For reference, here's Microsoft's System.Linq.Dynamic.DynamicQueryable.OrderBy source (Scott G's writeup link):
public static IQueryable<T> OrderBy<T>(
this IQueryable<T> source, string ordering, params object[] values)
{
return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
}
public static IQueryable OrderBy(
this IQueryable source, string ordering, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[]
{
Expression.Parameter(source.ElementType, "")
};
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings)
{
queryExpr = Expression.Call(
typeof(Queryable),
o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr,
Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}
Upvotes: 2
Views: 1287
Reputation: 2157
Is this what your looking for?
Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = t => t.OrderBy( String.Join(",", orderBy));
Upvotes: 2