using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace IRaCIS.Application.ExpressionExtend { public static class QueryableExtension { public static IOrderedQueryable OrderBy(this IQueryable query, string propertyName) { Type type = typeof(T); PropertyInfo property = type.GetProperty(propertyName); if (property == null) throw new ArgumentException(propertyName, "Not Exist"); return OrderBy(query, propertyName, false); } public static IOrderedQueryable OrderByDescending(this IQueryable query, string propertyName) { Type type = typeof(T); PropertyInfo property = type.GetProperty(propertyName); if (property == null) throw new ArgumentException(propertyName, "Not Exist"); return OrderBy(query, propertyName, true); } static IOrderedQueryable OrderBy(IQueryable query, string propertyName, bool isDesc) { string 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, System.Reflection.PropertyInfo memberProperty) { return query.OrderBy(_GetLamba(memberProperty)); } public static IOrderedQueryable OrderByDescendingInternal(IQueryable query, System.Reflection.PropertyInfo memberProperty) { return query.OrderByDescending(_GetLamba(memberProperty)); } static Expression> _GetLamba(System.Reflection.PropertyInfo memberProperty) { if (memberProperty.PropertyType != typeof(TProp)) throw new Exception(); var thisArg = Expression.Parameter(typeof(T)); var lamba = Expression.Lambda>(Expression.Property(thisArg, memberProperty), thisArg); return lamba; } } }