按匿名类型中的字段排序



我正在使用LINQ to Objects来聚合:

  var summary = from esc in objs
                where esc.time.Month == month && esc.time.Year == year
                group esc by esc.rlf_id into g
                select new { 
                  ID = g.Key, 
                  Total = g.Count(), 
                  Preventable = g.Where(a => a.preventable).Count() 
                };

我的查询像我期望的那样工作,但是我还想按匿名类型中的任意字段对查询进行排序。我找到了LINQ:命令匿名类型,但它是在VB。并且需要强烈指定要排序的字段。我可以概念化我想用这段伪代码完成的任务:

query = get all esc in obj
        aggregate into anonymous type with key ID
          ID = g.Key, Total = g.Count, Preventable = g.Count of preventable
        orderby inputField[0], (optional thenby inputField[1], ..., thenby inputField[n])

我如何完成:

  • 在LINQ查询中按匿名类型字段排序(完成-谢谢Marko)
  • 按匿名类型的任意字段进一步排序

我是开放的点语法或查询语法。

编辑:有了斯坦诺耶维奇的回答,我可以部分满足我的要求。我没有意识到我可以像那样将LINQ方法链接在一起。我现在能够(并从中获得预期的结果):

var summary = from esc in objs
              where esc.time.Month == month && esc.time.Year == year
              group esc by esc.rlf_id into g
              select new { 
                ID = g.Key, 
                Total = g.Count(), 
                Preventable = g.Where(a => a.preventable).Count() 
              };
summary = summary.OrderBy(e => e.Total); 

我需要的是一些东西,让我做:(伪代码)

summary = summary.<Order/Then>By<(optional)Descending>(e => e.<someUserInput>)

给定一个字符串,指定用户希望如何排序,显然我可以这样做:

if (sortQuery.Equals("Total", StringComparison.OrdinalIgnoresCase), bool descending) {
  summary = descending ? summary.OrderByDescending(e => e.Total) : summary.OrderBy(e => e.total)
} else if (sortQuery.Equals( /* ... etc */

然而,这最终是丑陋的快速,特别是因为我想用它来处理(可能几乎无限)越来越多的查询。它还需要考虑OrderBy()ThenBy()

我希望我正在使用c# 4,所以我现在可以使用动态…

我不知道是什么问题。在计算总结之后,您可以简单地

summary = summary.OrderBy(s => s.Total).ToList();

匿名类型的属性是立即可见的。如果您想传递它并遇到问题,那么最简单的解决方案是创建一个类,因为您知道它是什么样子的。如果你不想创建自定义类的某种原因,我想你可以使用Tuple,例如:

var summary = from esc in objs
                where esc.time.Month == month && esc.time.Year == year
                group esc by esc.rlf_id into g
                select new Tuple<long, int, int> ( 
                  g.Key, 
                  g.Count(), 
                  g.Where(a => a.preventable).Count() 
                );

则可以按.Item1.Item2等排序。尽管如此,我还是会使用自定义类,因为它更清楚发生了什么。

数据类型是匿名的这一事实并不重要,也不会改变问题。匿名类型是另一种类型(它只是有一个特殊的名称)。像其他类型一样,它在编译时是完全已知的!您可以阅读匿名类型与动态类型来了解更多关于匿名类型和动态类型的区别。

困难在于要调用的方法(例如OrderByOrderByDescending)及其参数(例如keySelector item => item.MyFieldName)仅在运行时才知道。

解决方案是使用反射

下面的代码将OrderByRules函数作为一个扩展方法实现,该方法应用于任何类型的IQueryable<T>集合(因此,只需使用AsQueryable<T>()操作符就可以应用于任何类型的IEnumerable<T>集合)。

第一个规则以一种特殊的方式处理,使用OrderBy操作符而不是ThenBy。然后递归地处理其余的。

排序操作符调用在函数OrderByFieldOrPropertyName中执行。根据字段或属性反射信息,我们构造一个形式为item => item.fieldName的lambda表达式。MakeGenericMethod函数用于构造具体方法。基本上,它允许您从OrderBy<T>切换到OrderBy<MyData>

我希望这能回答你的问题。

/// <summary>
/// Express an order rule based on property name
/// </summary>
public class OrderRule
{
    public OrderRule(string fieldOrPropertyName, bool descending)
    {
        FieldOrPropertyName = fieldOrPropertyName;
        Descending = descending;
    }
    public string FieldOrPropertyName { get; private set; }
    public bool Descending { get; private set; }
}
/// <summary>
/// Static class holding the OrderByRules extension method
/// </summary>
static public class MyLINQExtensions
{
    /// <summary>
    /// Order <paramref name="dataCollection"/> according to <paramref name="rules"/> sequence
    /// </summary>
    /// <typeparam name="T">Collection item type</typeparam>
    /// <param name="dataCollection">Queryable collection</param>
    /// <param name="rules">Order rules to apply</param>
    /// <returns>Ordered queryable collection</returns>
    public static IOrderedQueryable<T> OrderByRules<T>(this IQueryable<T> dataCollection, IEnumerable<OrderRule> rules)
    {
        if (!rules.Any())
            throw new ArgumentException("Rules list is empty", "rules");
        // apply first rule (special case: use OrderBy operator and not ThenBy)
        OrderRule rule = rules.First();
        MethodInfo orderOperator = rule.Descending ? OrderByDescendingMethodInfo : OrderByMethodInfo;
        IOrderedQueryable<T> orderedDataCollection = OrderByFieldOrPropertyName(dataCollection, orderOperator, rule.FieldOrPropertyName);
        // apply next rules recursivly
        return OrderByRulesRecursivly(orderedDataCollection, rules.Skip(1).ToList());
    }
    static IOrderedQueryable<T> OrderByFieldOrPropertyName<T>(IQueryable<T> dataCollection, MethodInfo orderOperator, string fieldOrPropertyName)
    {
        // member corresponding to fieldOrPropertyName
        MemberInfo memberInfo = typeof(T).GetField(fieldOrPropertyName);
        Type memberType = null;
        if (memberInfo == null)
            memberInfo = typeof(T).GetProperty(fieldOrPropertyName);
        else
            memberType = (memberInfo as FieldInfo).FieldType;
        if (memberInfo == null)
            throw new ArgumentException(String.Format("Field or property '{0}' doesn't exist on type '{1}'", fieldOrPropertyName, typeof(T)));
        else
            memberType = (memberInfo as PropertyInfo).PropertyType;
        // build lambda expression: item => item.fieldName
        ParameterExpression paramExp = Expression.Parameter(typeof(T));
        LambdaExpression keySelectorExp = Expression.Lambda(Expression.MakeMemberAccess(paramExp, memberInfo), paramExp);
        // build concrete MethodInfo from the generic one
        orderOperator = orderOperator.MakeGenericMethod(typeof(T), memberType);
        // invoke method on dataCollection
        return orderOperator.Invoke(null, new object[] {
            dataCollection,
            keySelectorExp
        }) as IOrderedQueryable<T>;
    }
    static IOrderedQueryable<T> OrderByRulesRecursivly<T>(IOrderedQueryable<T> dataCollection, List<OrderRule> rules)
    {
        if (!rules.Any())
            return dataCollection;
        // apply first rule
        OrderRule rule = rules.First();
        MethodInfo orderOperator = rule.Descending ? ThenByDescendingMethodInfo : ThenByMethodInfo;
        IOrderedQueryable<T> orderedDataCollection = OrderByFieldOrPropertyName(dataCollection, orderOperator, rule.FieldOrPropertyName);
        // apply next rules recursivly
        return OrderByRulesRecursivly(orderedDataCollection, rules.Skip(1).ToList());
    }
    /// <summary>
    /// Static constructor. Initialize Reflection informations about Order operators
    /// </summary>
    static MyLINQExtensions()
    {
        // public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
        OrderByMethodInfo = typeof(Queryable)
            .GetMethods()
            .First(m => m.Name == "OrderBy" && m.GetParameters().Count() == 2);
        // public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
        OrderByDescendingMethodInfo = typeof(Queryable)
            .GetMethods()
            .First(m => m.Name == "OrderByDescending" && m.GetParameters().Count() == 2);
        // public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
        ThenByMethodInfo = typeof(Queryable)
            .GetMethods()
            .First(m => m.Name == "ThenBy" && m.GetParameters().Count() == 2);
        // public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
        ThenByDescendingMethodInfo = typeof(Queryable)
            .GetMethods()
            .First(m => m.Name == "ThenByDescending" && m.GetParameters().Count() == 2);
    }
    static MethodInfo OrderByMethodInfo;
    static MethodInfo OrderByDescendingMethodInfo;
    static MethodInfo ThenByMethodInfo;
    static MethodInfo ThenByDescendingMethodInfo;
}

要编译,代码要求在头文件中声明以下命名空间:

using System.Linq.Expressions;
using System.Reflection;

现在你可以在你的上下文中使用OrderByRules:

var summaryOrdered = summary.OrderByRules(new List<OrderRule> {
    new OrderRule("Total", true),
    new OrderRule("Preventable", false)
});

这将按Total(降序)和可预防性(升序)对集合排序。

您可以使用以下扩展名:

试试这个:

// Optional properties for dynamic sorting
var orders = new[]
{
    new OrderByPropertyName {Desc = true, PropertyName = "Preventable"},
    new OrderByPropertyName {Desc = false, PropertyName = "ID"},
    new OrderByPropertyName {Desc = true, PropertyName = "Total"},
};
var firstOrder = orders.First();
var sortedSummary = firstOrder.Desc
    ? summary.AsQueryable().OrderByDescending(firstOrder.PropertyName)
    : summary.AsQueryable().OrderBy(firstOrder.PropertyName);
foreach (var order in orders.Except(new[] {firstOrder}))
{
    sortedSummary = order.Desc
        ? summary.OrderByDescending(order.PropertyName)
        : summary.OrderBy(order.PropertyName);
}
var result = sortedSummary.ToList();

相关内容

  • 没有找到相关文章

最新更新