6

Possible Duplicate:
Combining two expressions (Expression<Func<T, bool>>)

I have a method taking in a single Expression<Func<bool>> parameter

void MethodOne(Expression<Func<bool>> expression)

I've got multiple instances of Expression<Func<bool>>. How do I dynamically combine these expressions into a single Expression<Func<bool>> using Expression.OrElse (i.e. building up an expression tree)?

For example if I have two expressions such as

() => objectA.PropertyOneIsSet

and

() => objectB.PropertyTwoIsSet

I want the end result to be:

() => objectA.PropertyOneIsSet || objectB.PropertyTwoIsSet

so I can pass this to my method above.

Community
  • 1
  • 1
alex.tashev
  • 235
  • 3
  • 10
  • something I forgot to mention: I have N of these expressions (more than 2) and I want to OrElse all of them. – alex.tashev Nov 23 '12 at 14:58
  • See [this question](http://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool) which seems to include your problem... – Samuel Caillerie Nov 23 '12 at 14:53

2 Answers2

8

You can create ExpressionVisitor to combine queries. Check this msdn blog for more info: Combining Predicates (Answer 3). He talking about EF, but you can use it in your case

Uriil
  • 11,948
  • 11
  • 47
  • 68
3

You could use expressions.Any(x => x.CallMethod) in order to achieve this goal.

Damyan Bogoev
  • 688
  • 4
  • 12
  • I need to combine expressions selectively i.e. I don't want to always include all of the expressions in the end result. something like `if(someCondition) { result = result.OrElse(expressionN); }` – alex.tashev Nov 23 '12 at 15:05
  • You need to prepare this collection of expressions dynamically, based on some business rule / logic. But to execute the aggregated collection using the Any extension method. – Damyan Bogoev Nov 23 '12 at 15:07
  • I need the result to be an instance of Func>. Any() will return just a bool. – alex.tashev Nov 23 '12 at 15:08
  • 2
    Then you need something like that: http://www.albahari.com/nutshell/predicatebuilder.aspx – Damyan Bogoev Nov 23 '12 at 15:18