创建排序功能,IOrderedQueryable>
本文关键字:IOrderedQueryable IQueryable 排序 功能 创建 | 更新日期: 2023-09-27 18:35:36
我想在扩展方法中创建一个排序泛型 Func Creating Func<IQueryable<T>, IOrderedQueryable<T>>
:
public static Func<IQueryable<T>, IOrderedQueryable<T>> GetOrderByFunc<T>(this KeyValuePair<string, SortingType> keyValuePair)
{
//I expect the following result
//Func<IQueryable<T>, IOrderedQueryable<T>> orderby = q => q.OrderByDescending(c => c.Name);
//keyValuePair.Key is name of property in type of T that I should sort T by it
switch (keyValuePair.Value)
{
case SortingType.Ascending:
// Creating Ascending Sorting Func
break;
case SortingType.Descending:
// Creating Descending Sorting Func
break;
default :
break;
}
}
你能指导我,我该怎么做吗?
编辑:
此排序还包含 T 的导航属性的计数.
例如:
// keyValuePair.Key equals "User.Count"
// User is a navigation property of T
Func<IQueryable<T>, IOrderedQueryable<T>> orderby = q => q.OrderByDescending(c => c.User.Count);
编辑:
我更改了GetSelector
如下,但bodyExpression
中发生了异常。
public static Expression GetSelector<T>(string propertyName)
{
ParameterExpression parameter = Expression.Parameter(typeof(T));
if (propertyName.Contains("."))
{
propertyName = propertyName.Substring(0, propertyName.IndexOf("."));
Type navigationPropertyCollectionType = typeof(T).GetProperty(propertyName).PropertyType;
if (navigationPropertyCollectionType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
Expression countParameter = Expression.Parameter(navigationPropertyCollectionType, "c");
MemberExpression countExpression = Expression.Property(countParameter, "Count");
//Exception: Instance property 'Users(ICollection`1)' is not defined for type 'System.Int32'
var bodyExpression = Expression.Property(countExpression, propertyName, countParameter);
return Expression.Lambda(bodyExpression, parameter);
}
}
MemberExpression bodyMemberExpression = Expression.Property(parameter, typeof(T).GetProperty(propertyName));
return Expression.Lambda(bodyMemberExpression, parameter);
}
因此,我们需要的第一件事是一个方法,该方法可以获取选择器表达式,该表达式在给定属性名称时选择出该属性值。 它需要从头开始构建表达式:
public static Tuple<Expression, Type> GetSelector<T>(IEnumerable<string> propertyNames)
{
var parameter = Expression.Parameter(typeof(T));
Expression body = parameter;
foreach (var property in propertyNames)
{
body = Expression.Property(body,
body.Type.GetProperty(property));
}
return Tuple.Create(Expression.Lambda(body, parameter) as Expression
, body.Type);
}
请注意,由于这会导致属性链,因此该方法还返回最终属性的类型,因为从调用者的角度来看,这不是特别容易访问的信息。
因为我们在调用 Selector 时不知道属性的返回类型,所以我们别无选择,只能将此方法的返回类型保留为 Expression
。 我们不能把它投射到Expression<Func<T, Something>>
. 我们可以让它返回一个Expression<Func<T, object>>
,这将适用于所有选择引用类型的属性,但这不能对值类型进行框箱,因此在这些情况下它会引发运行时异常。
现在,因为我们不知道该表达式的确切类型,所以我们无法直接调用OrderBy
或OrderByDescending
。 我们需要通过反射和使用MakeGenericMethod
来获取这些方法,以便可以根据使用反射对该属性的检查,使用正确的类型创建它们。
public static Func<IQueryable<T>, IOrderedQueryable<T>> GetOrderByFunc<T>(
this Tuple<IEnumerable<string>, SortingType> sortCriteria)
{
var selector = GetSelector<T>(sortCriteria.Item1);
Type[] argumentTypes = new[] { typeof(T), selector.Item2 };
var orderByMethod = typeof(Queryable).GetMethods()
.First(method => method.Name == "OrderBy"
&& method.GetParameters().Count() == 2)
.MakeGenericMethod(argumentTypes);
var orderByDescMethod = typeof(Queryable).GetMethods()
.First(method => method.Name == "OrderByDescending"
&& method.GetParameters().Count() == 2)
.MakeGenericMethod(argumentTypes);
if (sortCriteria.Item2 == SortingType.Descending)
return query => (IOrderedQueryable<T>)
orderByDescMethod.Invoke(null, new object[] { query, selector.Item1 });
else
return query => (IOrderedQueryable<T>)
orderByMethod.Invoke(null, new object[] { query, selector.Item1 });
}
您需要使用表达式
public static Func<IQueryable<T>, IOrderedQueryable<T>> GetOrderByFunc<T>(this KeyValuePair<string, SortingType> keyValuePair)
{
Func<IQueryable<T>, IOrderedQueryable<T>> result;
var p1 = Expression.Parameter(typeof (T), "p1");
var prop = Expression.PropertyOrField(p1, keyValuePair.Key);
var lambada = Expression.Lambda<Func<T, object>>(prop, new ParameterExpression[] {p1});
//keyValuePair.Key is name of property in type of T that I should sort T by it
switch (keyValuePair.Value)
{
case SortingType.Ascending:
result = source => source.OrderBy(lambada);
break;
case SortingType.Descending:
result = source => source.OrderByDescending(lambada);
break;
default:
throw new NotImplementedException();
break;
}
return result;
}