简体   繁体   English

嵌套在IEnumerable中的动态Linq to OrderBy对象

[英]Dynamic Linq to OrderBy Object Nested in IEnumerable

I am trying to write some dynamic linq to order by a property of a list item, for use with NHibernate 我正在尝试编写一些动态linq以通过列表项的属性进行排序,以便与NHibernate一起使用

public class Company
{
    public string Name { get; set; }
    public List<Employee> Employees { get; set; }
}

public class Employee
{
    public string Name{get; set;}
    public string PayrollNo{get; set;}

}

In this example it would be like to return all Companies and order by PayrollNumber. 在此示例中,将要按薪水单编号返回所有公司和订单。

The Repository Method would look like this with standard linq. 使用标准linq,存储库方法将看起来像这样。

var companies = session.Query<Company>()
    .OrderBy(x => x.Pieces.FirstOrDefault().PayrollNo)
    .FetchMany(x => x.Employees)

I would like to change this to dynamic linq to order by column headers 我想将其更改为动态linq以按列标题排序

 var companies = session.Query<Company>()
    .OrderByName("Employees.PayrollNo"), isDescending)
    .FetchMany(x => x.Employees)

I took an approach similar to the answer in Dynamic LINQ OrderBy on IEnumerable<T> Writing an extension method 在IEnumerable <T>上采用了与Dynamic LINQ OrderBy中的答案类似的方法编写扩展方法

But then drilled down with recursion 但是后来又递归了

    public static IQueryable<T> OrderByName<T>(this IQueryable<T> source, string propertyName, Boolean isDescending)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var properties = propertyName.Split('.');
        var type = GetNestedProperty(properties, typeof(T));
        var arg = Expression.Parameter(type.GetProperty(properties.Last()).PropertyType, "x");
        var expr = Expression.Property(arg, properties.Last());

        Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

        String methodName = isDescending ? "OrderByDescending" : "OrderBy";
        object result = typeof(Queryable).GetMethods().Single(
            method => method.Name == methodName
                    && method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] { source, lambda });
        return (IQueryable<T>)result;
    }


    //Walk the tree of properties looking for the most nested in the string provided
    static Type GetNestedProperty(string[] propertyChain, Type type) 
    {
        if (propertyChain.Count() == 0)
            return type;

        string first = propertyChain.First();
        propertyChain = propertyChain.Skip(1).ToArray(); //strip off first element

        //We hare at the end of the hierarchy
        if (propertyChain.Count() == 0)
            return GetNestedProperty(propertyChain, type);

        //Is Enumerable
        if (type.GetProperty(first).PropertyType.GetInterfaces().Any(t => t.Name == "IEnumerable"))
            return GetNestedProperty(
                propertyChain,
                type.GetProperty(first).PropertyType.GetGenericArguments()[0]);

        return GetNestedProperty(
            propertyChain,
            type.GetProperty(first).PropertyType.GetProperty(propertyChain.FirstOrDefault()).GetType());

    }

I am having difficulty generating the expression in the OrderByName extension method. 我在OrderByName扩展方法中生成表达式时遇到困难。 I have tried quite a few things now, but the problem is that Payroll number does not exist in the Company class. 我现在已经尝试了很多事情,但是问题是公司类中不存在工资单号。

Is what I am trying to achieve even possible? 我正在努力实现的目标是否可能?

Any help with this would be greatly appreciated. 任何帮助,将不胜感激。

NHibernate has other query APIs which are better for this. NHibernate还有其他更好的查询API。

string property = "Employees.PayrollNo";

var query = session.QueryOver<Company>()
    .Fetch(x => x.Employees).Eager;

// Join on the associations involved
var parts = property.Split('.');
var criteria = query.UnderlyingCriteria;
for (int i = 0; i < parts.Length - 1; i++)
{
    criteria.CreateAlias(parts[i], parts[i]);
}
// add the order
criteria.AddOrder(new Order(property, !isDescending));

var companies = query.List();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM