【问题标题】:Expression trees, apply predicate to property表达式树,将谓词应用于属性
【发布时间】:2022-01-21 22:55:59
【问题描述】:

假设我有一个存储为 Expression> 的谓词,我想将其应用于 objA 的属性,但我只能访问 Expression,并且我知道 objA 具有 typeB 类型的属性 propB。

如何组合这些表达式树?

一个更好地解释我想要达到的目标的例子:

Expression<Func<TypeB, bool>> expr1 = (b => b.Where(b.propC.HasFlag(flag))
Expression<Func<TypeB, bool>> expr2 = (b => b.Where(b.propD != null)
...
// Now let's combine these with Or operator
InvocationExpression invocationExpression = Expression.Invoke((Expression) expr2.Expand<Func<typeB, bool>>(), expr1.Parameters.Cast<Expression>());
Expression<Func<typeB, bool>> combinedExpr = Expression.Lambda<Func<typeB, bool>>((Expression) Expression.OrElse(expr1.Body, (Expression) invocationExpression), (IEnumerable<ParameterExpression>) expr1.Parameters);

// To complete my task I need to pass an argument of type Expression<Func<TypeA, bool>> to method, but I am not sure how to build such an expression tree.
// That also could be written as a literal like that:
AddCriterion(objA => objA.propB.Where(b => b.propC.HasFlag(flag) || b.propD != null))

【问题讨论】:

  • 这真的没有意义。您如何将谓词“存储为”一种类型但只能“访问”另一种类型?
  • 很抱歉造成混淆。我会尽力解释我的意思。

标签: c# .net


【解决方案1】:

我在另一个涵盖完全相同主题的堆栈溢出问题中找到了答案。

Combine Expression (Expression<Func<TIn,TOut>> with Expression<Func<TOut, bool>>)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多