我是表达式树的新手。 我需要根据字符串长度和字符串来排序我的集合。 我不想为每个实体重复我的代码。 有谁知道怎么用表达式树来写它?
像这样的东西
public static IQueryable<T> OrderByPropertyOrField<T>(this IQueryable<T> queryable,
string propertyOrFieldName, bool ascending = true)
{
var elementType = typeof(T);
var orderByMethodName = ascending ? "OrderBy" : "OrderByDescending";
var parameterExpression = Expression.Parameter(elementType);
var propertyOrFieldExpression = Expression.PropertyOrField(parameterExpression, propertyOrFieldName);
var selector = Expression.Lambda(propertyOrFieldExpression, parameterExpression);
var orderByExpression = Expression.Call(typeof(Queryable), orderByMethodName,
new[] { elementType, propertyOrFieldExpression.Type }, queryable.Expression, selector);
return queryable.Provider.CreateQuery<T>(orderByExpression);
}
答案 0 :(得分:0)
如果在按字符串长度排序之后需要按字符串值排序,则需要调用另一个Quryable方法-ThenBy
或ThenByDescending
,具体取决于ascending
的值。接下来的代码将创建该顺序:
public static class QueryableExtensions
{
public static IQueryable<T> OrderByPropertyOrField<T>(this IQueryable<T> queryable,
string propertyOrFieldName, bool ascending = true)
{
var parameter = Expression.Parameter(queryable.ElementType, "x");
var selector = Expression.PropertyOrField(parameter, propertyOrFieldName);
var getLength = Expression.PropertyOrField(selector, "Length");
var orderByLength = CreateOrderExpression(parameter,
typeof(int),
queryable.Expression, // order source collection
getLength,
ascending ? "OrderBy" : "OrderByDescending");
var orderByValue = CreateOrderExpression(parameter,
typeof(string),
orderByLength, // order previous collection
selector,
ascending ? "ThenBy" : "ThenByDescending");
return queryable.Provider.CreateQuery<T>(orderByValue);
}
private static Expression CreateOrderExpression(ParameterExpression parameter, Type keyType, Expression collection, Expression selector, string methodName)
{
return Expression.Call(
typeof(Queryable),
methodName,
new[] { parameter.Type, keyType },
collection,
Expression.Lambda(selector, parameter)
);
}
}