Home > Software engineering >  Multiple Expression.Or
Multiple Expression.Or

Time:02-03

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.

CodePudding user response:

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.

CodePudding user response:

It looks like you'd better use the Expression.OrElse() method. The method Expression.Or() represents a bitwise OR operation, i.e. x.Parameter1 == "Some text" | x.Parameter2 == "Some text"

var condition1 = Expression.Equal(Expression.Parameter(typeof(string), "parameter1"),
    Expression.Constant("Some text 1"));
var condition2 = Expression.Equal(Expression.Parameter(typeof(string), "parameter2"),
    Expression.Constant("Some text 2"));
var condition3 = Expression.Equal(Expression.Parameter(typeof(string), "parameter3"),
    Expression.Constant("Some text 3"));

var result = Expression.OrElse(condition1, Expression.OrElse(condition2, condition3));
  • Related