ArgumentException 调用 Expression.IfThenElse

ArgumentException calling Expression.IfThenElse

我正在尝试构建此 LINQ 查询:

Result = Result.Where(Function(Row) If(IsDBNull(Row(7)), False, Convert.ToInt32(Row(7)) > 10))

ResultIEnumerable(Of Object()).

我设法用这段代码构建了表达式,但在最后一行,我收到一条错误消息。

我的代码是这样的:

Dim whereMethod = GetType(Queryable).GetMethods(BindingFlags.Public Or BindingFlags.Static).First(Function(m) m.Name = "Where").MakeGenericMethod(GetType(Object()))
Dim convertMethod As MethodInfo = Nothing
Dim rowParameter = Expression.Parameter(GetType(Object()), "Row")
Dim isdbnullMethod As MethodInfo = GetType(System.Convert).GetMethod("IsDBNull", New Type() {GetType(Object)})
Dim expr As Expression = Nothing
Dim tempexpr As Expressions.LambdaExpression = Nothing
convertMethod = GetType(System.Convert).GetMethod("ToInt32", New Type() {GetType(Object)})

tempexpr = Expression.Lambda(Expression.IfThenElse(
                             Expression.Call(isdbnullMethod,
                                 Expression.ArrayAccess(rowParameter, Expression.Constant(7))),
                             Expression.Constant(False),
                             Expression.GreaterThan(
                                 Expression.Call(
                                     convertMethod,
                                     Expression.ArrayAccess(rowParameter, Expression.Constant(7))),
                                 Expression.Constant(10))),
                         rowParameter)

然后我打电话:

expr = Expression.Call(whereMethod, Result.AsQueryable.Expression, Expression.Lambda(tempexpr.Body, rowParameter))

在这一行我得到这个错误:

可能是什么问题?没有 IfThenElse 它可以工作。还有这个:

Result = Result.Where(Function(Row) Convert.ToInt32(Row(7)) > 10)

编辑

这是因为 If 运算符是一个 "Action" 方法并且 returns 不是一个值吗?

顺便说一句。 Expression.IfThenElse 使用 IIf 函数。我如何使用 If 功能?

编辑二

我想,我找到了:Expression.Condition。它也使用 IIf,但是有了这个,我没有例外。

你的 Edit II 是正确的:Expression.IfThenElse returns void, making the whole expression an Action. Expression.Condition returns 无论 ifTrue 参数中的类型是什么,使你的表达式 Expression(Of Func(Of Boolean)),这就是你想要的。

顺便说一句,我不相信它真的在调用 IIf 函数。这只是正在发生的事情的调试视图。我不认为它真的调用了那些 VB.NET-only 方法