How to store Microsoft's Dynamic Linq's OrderBy in a variable?

c# dynamic-linq linq

Question

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);
}
1
2
3/18/2015 6:51:54 PM

Accepted Answer

Is this what your looking for?

Func<IQueryable<T>, IOrderedQueryable<T>> _orderBy = t => t.OrderBy( String.Join(",", orderBy));
2
3/13/2015 2:41:34 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow