CostCalculationItem/IRaCIS.Core.Application/_ExpressionExtend/QueryableExtension.cs

65 lines
2.4 KiB
C#

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