1

Let's say that I have a predicate stored as Expression<Func<typeB, bool>> that I would like to apply to the property of objA, but I can only control the Expression<Func<TypeA, bool>, within I would like to embed that predicate. Type typeA has property propB of type typeB.

How to combine these expression trees?

An example to better explain what I would like to achieve:

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))
proximab
  • 1,865
  • 1
  • 13
  • 18

1 Answers1

1

I've found the answer in another stack overflow question that covers exactly the same topic.

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

proximab
  • 1,865
  • 1
  • 13
  • 18