使用Dynamic Linq进行自然排序,包括多个排序参数

时间:2014-08-04 15:50:59

标签: c# linq sorting dynamic-linq

正如标题所描述的,有什么方法可以使用Dynamic Linq实现自然排序,包括支持多个排序参数?

最好我想做这样的事情(使用自定义IComparer):

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

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

2 个答案:

答案 0 :(得分:3)

DynamicLinq 没有以OrderBy作为参数的方法IComparer<T>,因此您无法传递自定义比较器,但您可以像这样修改源

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

并像这样使用

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

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

NaturalSort应该在哪里实施IComparer<T> 关于实现叙述排序,你可以看到Natural Sort Order in C#

注意:但我不确定这是否适用于其他提供商,例如db

答案 1 :(得分:-2)

看起来你想要这个:

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

基本上,您希望使用OrderByOrderByDescending作为第一个排序参数,然后使用ThenByThenByDescending作为其余参数。

(请注意,此处不需要AsQueryable,因为List<T>扩展了IEnumerable<T>。)