Building 'flat' rather than 'tree' LINQ expressions

Posted by Ian Gregory on Stack Overflow See other posts from Stack Overflow or by Ian Gregory
Published on 2010-05-30T19:51:19Z Indexed on 2010/05/30 20:12 UTC
Read the original article Hit count: 261

Filed under:
|
|

I'm using some code (available here on MSDN) to dynamically build LINQ expressions containing multiple OR 'clauses'.

The relevant code is

var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));

var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

This generates a LINQ expression that looks something like this:

(((((ID = 5) OR (ID = 4)) OR (ID = 3)) OR (ID = 2)) OR (ID = 1))

I'm hitting the recursion limit (100) when using this expression, so I'd like to generate an expression that looks like this:

(ID = 5) OR (ID = 4) OR (ID = 3) OR (ID = 2) OR (ID = 1)

How would I modify the expression building code to do this?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ