1 回答
TA贡献1785条经验 获得超4个赞
由于类型在编译时未知,因此您将无法使用强类型返回类型,例如Expression<Func<T,TKey>>.
public static class ExpressionTreesExtension {
static readonly Type funcTTResult = typeof(Func<,>);
public static IOrderedQueryable<T> OrderByProperty<T>(this IEnumerable<T> enumerable, string propertyName) {
var itemType = typeof(T);
var propertyInfo = itemType.GetProperty(propertyName);
var propertyType = propertyInfo.PropertyType;
// Func<T,TPropertyType>
var delegateType = funcTTResult.MakeGenericType(itemType, propertyType);
// T x =>
var parameterExpression = Expression.Parameter(itemType, "x");
// T x => x.Property
var propertyAccess = Expression.Property(parameterExpression, propertyInfo);
// Func<T,TPropertyType> = T x => x.Property
var keySelector = Expression.Lambda(delegateType, propertyAccess, parameterExpression);
var query = enumerable.AsQueryable();
// query.OrderBy(x => x.Property)
MethodCallExpression orderByExpression = Expression.Call(
typeof(Queryable),
"OrderBy",
new[] { query.ElementType, propertyInfo.PropertyType },
query.Expression, keySelector);
// Create an executable query from the expression tree.
return (IOrderedQueryable<T>)query.Provider.CreateQuery<T>(orderByExpression);
}
}
并使用像
//IEnumerable<Person> records... var data = records.OrderByProperty("Name");
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报