1

I have the following function to order an array based on a property specified by a string:

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 });
}

I have to following test class:

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; }
}

The order by works for a property of the "TestClass". How should I modify the code so that I can order by the properties of the "InnerClass" subclass?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
kovacs lorand
  • 741
  • 7
  • 23

0 Answers0