-->

Natural sort with Dynamic Linq including multiple

2019-09-09 10:20发布

问题:

As the title describes, is there any way I can achieve natural sort using Dynamic Linq including support for multiple sorting parameters?

Preferably I would like to do something like this (using a custom IComparer):

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

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

回答1:

DynamicLinq does not have method OrderBy that takes IComparer<T> as parameters, so you can't pass custom comparer, but you can modify source like this

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);
}

and use it like this

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

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

where NaturalSort should implement IComparer<T> about implementing narural sort you can see this Natural Sort Order in C#

NOTE: but i'm not sure that this will be work with other providers, like db



回答2:

It looks like you want this:

invoices = invoices
    .OrderBy(invoice => invoice.SortingParameter1, new NaturalSort())
    .ThenBy(invoice => invoice.SortingParameter2, new NaturalSort())
    .ToList();

Basically, you want to use OrderBy or OrderByDescending for the first sorting parameter, and then ThenBy or ThenByDescending for the rest of them.

(Note that AsQueryable is not needed here, as List<T> extends IEnumerable<T>.)