5

オブジェクト会社のテーブルをWeb ページに表示しており、動的 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 に答える