Natural sort with Dynamic Linq including multiple sorting parameters

c# dynamic-linq linq sorting

Question

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
1
8/4/2014 7:20:49 PM

Accepted Answer

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

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