如何为子属性创建OrderBy keySelector?

时间:2014-08-06 10:52:57

标签: c# linq

我有以下函数来根据字符串指定的属性对数组进行排序:

private static MethodInfo OrderByMethod = typeof(Enumerable)
            .GetMethods(BindingFlags.Public | BindingFlags.Static)
            .Where(method => method.Name == "OrderBy"
                   && method.GetParameters().Length == 2)
            .Single();

public static IOrderedEnumerable<TSource> OrderByProperty<TSource>(IEnumerable<TSource> source, string propertyName)
{
    // TODO: Lots of validation :)
    PropertyInfo property = typeof(TSource).GetProperty(propertyName);
    MethodInfo getter = property.GetGetMethod();
    Type propType = property.PropertyType;
    Type funcType = typeof(Func<,>).MakeGenericType(typeof(TSource), propType);
    Delegate func = Delegate.CreateDelegate(funcType, getter);
    MethodInfo constructedMethod = OrderByMethod.MakeGenericMethod(
        typeof(TSource), propType);
    return (IOrderedEnumerable<TSource>)constructedMethod.Invoke(null,
        new object[] { source, func });
}

我必须关注测试类:

public class TestClass
{
    public int Szam { get; set; }
    public string Szoveg { get; set; }
    public InnerClass BelsoData { get; set; }
}

public class InnerClass
{
    public string InnerText { get; set; }
}

按照#34; TestClass&#34;的属性工作的顺序。我应该如何修改代码,以便我可以通过&#34; InnerClass&#34;的属性进行排序。子类

0 个答案:

没有答案