1

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();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Philip
  • 33
  • 4
  • _DynamicLinq_ does not have method `OrderBy` that takes _IComparer_ as parameters, so you can't pass custom comparer, but you can modify source how you want – Grundy Aug 06 '14 at 13:47

2 Answers2

4

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

Community
  • 1
  • 1
Grundy
  • 13,356
  • 3
  • 35
  • 55
  • @Philip, I want to once again draw attention to the fact that I'm not sure that it will work with the database – Grundy Aug 07 '14 at 13:20
  • It's OK cause I´m only using it to sort objects in ILists. One weird thing though. It's working perfectly on my developing maching but when I publish it I get the following exception: "No generic method 'OrderBy' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.". All the dll's are up to date. – Philip Aug 07 '14 at 13:38
  • @Philip, can you see in dll with `DynamicLinq` if there this method? also where you add this code? in source and recompile it? or somewhere else? – Grundy Aug 07 '14 at 13:45
  • Yes, I added your code to the DynamicQueryable class in System.Linq.Dynamic namespace so your methods are in there with all the other Dynamic Linq-methods. Very strange.. – Philip Aug 07 '14 at 13:49
  • @Philip, try compare dll from developer machine with dll after publish, also possibly after publish you have reference on defferent dlls – Grundy Aug 07 '14 at 13:51
  • Solved it! My IComparer only implemented IComparer and one the sort fields was of type int?. Why it worked in debugging I don't know. – Philip Aug 07 '14 at 14:35
  • @Philip possibly different class or query on development and after publish :-) – Grundy Aug 07 '14 at 15:00
-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>.)

Jashaszun
  • 9,207
  • 3
  • 29
  • 57
  • No sorry thats not what I want. I want to use the sortingparameters as strings since the parameters will be unknown until runtime. Dynamic Linq makes this work, however I cant find a way to use a custom IComparer to be able to achieve "Natural sort" / "Natural Numeric Sort". – Philip Aug 05 '14 at 09:09