static class Program
{
static void Main(string[] args)
{
string[] array = { "aaa", "bb", "c" };
foreach (var item in array.AsQueryable().OrderBy("Length"))
{
Console.WriteLine(item);
}
Console.ReadLine();
}
public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string prop)
{
var member = typeof(T).GetProperty(prop);
return (IQueryable<T>)typeof(Program)
.GetMethod("OrderByCore", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(typeof(T), member.PropertyType)
.Invoke(null, new object[] { query, member });
}
private static IQueryable<T> OrderByCore<T, TMember>(IQueryable<T> query, MemberInfo memb
{
ParameterExpression item;
return query.OrderBy<T, TMember>(Expression.Lambda<Func<T, TMember>>(
Expression.MakeMemberAccess(item = Expression.Parameter(typeof(T), "item"), membe
}
}
{
static void Main(string[] args)
{
string[] array = { "aaa", "bb", "c" };
foreach (var item in array.AsQueryable().OrderBy("Length"))
{
Console.WriteLine(item);
}
Console.ReadLine();
}
public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string prop)
{
var member = typeof(T).GetProperty(prop);
return (IQueryable<T>)typeof(Program)
.GetMethod("OrderByCore", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(typeof(T), member.PropertyType)
.Invoke(null, new object[] { query, member });
}
private static IQueryable<T> OrderByCore<T, TMember>(IQueryable<T> query, MemberInfo memb
{
ParameterExpression item;
return query.OrderBy<T, TMember>(Expression.Lambda<Func<T, TMember>>(
Expression.MakeMemberAccess(item = Expression.Parameter(typeof(T), "item"), membe
}
}