Search code examples
c#entity-frameworklinqexpression

Multiple Expression.Or


How to build an expression which will produce the following statement?

x => x.Parameter1 == "Some text" || x.Parameter2 == "Some text" || x.Parameter3 == "Some text"

It's not hard to do x =>, but how to create those many OR operators?

I know we have Expression.Or method, but it only accepts 2 arguments.

Thanks.


Solution

  • So you just compile them together

    psuedo code:

    firstOr = Expression.OrElse(x.Parameter2 == "some test", x.Parameter3 == "sometest")
    
    secondOr = Expression.OrElse(firstOr, x.Parameter1 == "Some text");
    

    Then all you do is evaluate the secondOr

    These are expression trees , and therefor you compose them together.

    when you have multiple elements, segment as you would with a mathematical expression, put parenthesis around parts:

    1 + 2 + 5 = 8

    this is

    (1 + 2) + 5 = 8

    So we've turned 1 expression into a composition of 2 expressions.