using System.Linq.Expressions; using System.Reflection; namespace ServiceLib.Common { public static class QueryableExtension { public static IOrderedQueryable OrderBy(this IQueryable query, string propertyName) { return _OrderBy(query, propertyName, false); } public static IOrderedQueryable OrderByDescending(this IQueryable query, string propertyName) { return _OrderBy(query, propertyName, true); } private static IOrderedQueryable _OrderBy(IQueryable query, string propertyName, bool isDesc) { var methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal"; var memberProp = typeof(T).GetProperty(propertyName); var method = typeof(QueryableExtension).GetMethod(methodname) .MakeGenericMethod(typeof(T), memberProp.PropertyType); return (IOrderedQueryable)method.Invoke(null, new object[] { query, memberProp }); } public static IOrderedQueryable OrderByInternal(IQueryable query, PropertyInfo memberProperty) {//public return query.OrderBy(_GetLambda(memberProperty)); } public static IOrderedQueryable OrderByDescendingInternal(IQueryable query, PropertyInfo memberProperty) {//public return query.OrderByDescending(_GetLambda(memberProperty)); } private static Expression> _GetLambda(PropertyInfo memberProperty) { if (memberProperty.PropertyType != typeof(TProp)) throw new Exception(); var thisArg = Expression.Parameter(typeof(T)); var lambda = Expression.Lambda>(Expression.Property(thisArg, memberProperty), thisArg); return lambda; } } }