5

我在网页中显示了一个对象公司表,我正在使用动态 Linq OrderBy 对每个属性进行排序。我正在使用此代码https://stackoverflow.com/a/233505/265122

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
    return ApplyOrder<T>(source, property, "OrderBy");
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
    return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
    return ApplyOrder<T>(source, property, "ThenBy");
}
public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
    return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) {
    string[] props = property.Split('.');
    Type type = typeof(T);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = arg;
    foreach(string prop in props) {
        // use reflection (not ComponentModel) to mirror LINQ
        PropertyInfo pi = type.GetProperty(prop);
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;
    }
    Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

    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 (IOrderedQueryable<T>)result;
}

这很好,但我也想根据员工人数对公司进行排序。

像这样:query.OrderBy("Employees.Count")

到目前为止,我尝试动态调用 Count 方法,但没有成功。

我修改了这样的代码:

foreach(string prop in props)
{
    if (prop == "Count")
    {
        var countMethod = (typeof(Enumerable)).GetMethods().First(m => m.Name == "Count").MakeGenericMethod(type);
        expr = Expression.Call(countMethod, expr);
        break;
    }

    // Use reflection (not ComponentModel) to mirror LINQ.
    PropertyInfo pi = type.GetProperty(prop);
    expr = Expression.Property(expr, pi);
    type = pi.PropertyType;
}

但我有一个例外expr = Expression.Call(countMethod, expr);

例外是:

ArgumentException
Expression of type 'System.Collections.Generic.ICollection`1[Employee]'
cannot be used for parameter of type
'System.Collections.Generic.IEnumerable`1[System.Collections.Generic.ICollection`1
[Employee]]' of method 'Int32 Count[ICollection`1]
System.Collections.Generic.IEnumerable`1[System.Collections.Generic.ICollection`1
Employee]])'

关于如何实现这一目标的任何想法?

4

1 回答 1

3

从下面的要点中,我找到了一种简单的方法,可以将所有基本类型和接口的属性展平,如本文所示

所以我实现了 PropertyInfo 的扩展方法,它将返回类型继承的所有接口和基类的所有属性。问题是 IList 没有 Count 属性,但 iCollection 有。将public static PropertyInfo[] GetPublicProperties(this Type type)平展所有属性,我们从那里得到正确的属性,这应该适用于现在的任何属性,而不仅仅是 Count。

public class Program
{
    private static IList<Company> _companies;


    static void Main(string[] args)
    {
        var sort = "Employees.Count";
        _companies = new List<Company>();


        _companies.Add(new Company
                           {
                               Name = "c2",
                               Address = new Address {PostalCode = "456"},
                               Employees = new List<Employee> {new Employee(), new Employee()}
                           });
        _companies.Add(new Company
                           {
                               Name = "c1",
                               Address = new Address {PostalCode = "123"},
                               Employees = new List<Employee> { new Employee(), new Employee(), new Employee() }
                           });

        //display companies
        _companies.AsQueryable().OrderBy(sort).ToList().ForEach(c => Console.WriteLine(c.Name));


        Console.ReadLine();
    }
}


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

public class Employee{}


public class Address
{
    public string PostalCode { get; set; }
}


public static class OrderByString
{
    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder<T>(source, property, "OrderBy");
    }


    public static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
    {
        string[] props = property.Split('.');
        Type type = typeof(T);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;

        foreach (string prop in props)
        {
            // use reflection (not ComponentModel) to mirror LINQ
            PropertyInfo pi = type.GetPublicProperties().FirstOrDefault(c => c.Name == prop);
            if (pi != null)
            {
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            else { throw new ArgumentNullException(); }
        }
        Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);


        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 (IOrderedQueryable<T>)result;
    }

    public static PropertyInfo[] GetPublicProperties(this Type type)
    {
        if (type.IsInterface)
        {
            var propertyInfos = new List<PropertyInfo>();

            var considered = new List<Type>();
            var queue = new Queue<Type>();
            considered.Add(type);
            queue.Enqueue(type);
            while (queue.Count > 0)
            {
                var subType = queue.Dequeue();
                foreach (var subInterface in subType.GetInterfaces())
                {
                    if (considered.Contains(subInterface)) continue;

                    considered.Add(subInterface);
                    queue.Enqueue(subInterface);
                }

                var typeProperties = subType.GetProperties(
                    BindingFlags.FlattenHierarchy
                    | BindingFlags.Public
                    | BindingFlags.Instance);

                var newPropertyInfos = typeProperties
                    .Where(x => !propertyInfos.Contains(x));

                propertyInfos.InsertRange(0, newPropertyInfos);
            }

            return propertyInfos.ToArray();
        }

        return type.GetProperties(BindingFlags.FlattenHierarchy
            | BindingFlags.Public | BindingFlags.Instance);
    }
}
于 2012-10-10T21:54:17.507 回答