Natural sort with Dynamic Linq including multiple sorting parameters

c# dynamic-linq linq sorting

Question

Is there a method, as the question's title suggests, to use Dynamic Linq to do a natural sort that supports numerous sorting parameters?

I would want to carry out the following (using a unique IComparer):

List<Invoice> invoices = Provider.GetInvoices();

invoices = invoices
  .AsQueryable()
  .OrderBy("SortingParameter1 ASC, SortingParamaeter 2 ASC", new NaturalSort())
  .ToList();
1
1
8/4/2014 7:20:49 PM

Accepted Answer

DynamicLinq is without a method.OrderBy that demandsIComparer<T> as arguments, making it impossible to provide a custom comparer, however you may change the source as shown above

public static IQueryable<T> OrderBy<T,ComparerType>(this IQueryable<T> source, IComparer<ComparerType> comparer, string ordering, params object[] values)
{
    return (IQueryable<T>)OrderBy((IQueryable)source, comparer, ordering, values);
}

public static IQueryable OrderBy<ComparerType>(this IQueryable source, IComparer<ComparerType> comparer, 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)), Expression.Constant(comparer));
            methodAsc = "ThenBy";
            methodDesc = "ThenByDescending";
        }
    return source.Provider.CreateQuery(queryExpr);
}

Then use it in this way

List<Invoice> invoices = Provider.GetInvoices();

invoices = invoices.AsQueryable()
                   .OrderBy(new NaturalSort(), "SortingParameter1 ASC, SortingParamaeter 2 ASC")
                   .ToList();

where NaturalSort to put into practiceIComparer<T> To learn more about how to implement the rural sort, visit this C# Natural Sort Order.

I'm not sure whether this will work with other providers, like database, however.

4
5/23/2017 11:54:34 AM


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