Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq to实体中带SwitchExpression的OrderBy_C#_Linq_Linq To Entities_Expression_Expression Trees - Fatal编程技术网

C# Linq to实体中带SwitchExpression的OrderBy

C# Linq to实体中带SwitchExpression的OrderBy,c#,linq,linq-to-entities,expression,expression-trees,C#,Linq,Linq To Entities,Expression,Expression Trees,我需要为enum定制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);

我需要为enum定制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);
    }
我得到一个错误:

类型为“Switch”的未知LINQ表达式

是否有另一种方法可以生成将转换为sql构造“CASE-WHEN…”的顺序表达式?

尝试表达式。条件() 我认为,如果在匿名投影中使用,则会出现这种情况

filtered.MyOrderBy("field1", typeof(FieldState)).ToList();