我需要为枚举制作自定义orderby。我尝试使用SwitchExpression:
public static IQueryable<T> MyOrderByEnum<T>(this IQueryable<T> source, string propName, Type enumType)
{
var type = typeof (T);
var property = type.GetProperty(propName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.Property(parameter, property);
var enumValues = Enum.GetValues(enumType);
var switchCases = new SwitchCase[enumValues.Length];
int i = 0;
foreach (var val in enumValues)
{
switchCases[i] = Expression.SwitchCase(
Expression.Constant(val.ToDisplay()),
Expression.Constant(val)
);
i++;
}
var switchExpr1 =
Expression.Switch(
propertyAccess,
Expression.Constant(""),
switchCases
);
var orderByExp1 = Expression.Lambda(switchExpr1, parameter);
MethodCallExpression resultExp = Expression.Call(typeof (Queryable), "OrderBy", new[] {type, orderByExp1.Body.Type}, source.Expression, orderByExp1);
return (IOrderedQueryable<T>) source.Provider.CreateQuery(resultExp);
}
但是当我执行
时filtered.MyOrderBy("field1", typeof(FieldState)).ToList();
我收到错误:
“Switch”类型的未知LINQ表达式。
是否有另一种方法可以将命令表达式转换为sql构造“CASE WHEN ......”?
答案 0 :(得分:1)
尝试Expression.Condition(https://msdn.microsoft.com/en-us/library/bb340500%28v=vs.110%29.aspx) 我认为转换为CASE如果在匿名投影中使用