Dynamically building ‘Or’ Expressions in LINQ

One common question on
Stackoverflow concerns the
creation of a LINQ expression that logically Ors together a set of
predicates. The need stated is to be able to build such an expression
dynamically. Creating the ‘And’ version is easy, you simply stack
multiple ‘.Where‘ clauses onto an expression as you add each
predicate. You can’t do the same for ‘Or’. The common responses are ‘use
LINQKit’ or ‘use Dynamic LINQ’. LINQKit however adds the unfortunate
‘.AsExpandable()’ into the expression which can cause problems in some
circumstances, and Dynamic LINQ is not strongly-typed so doesn’t survive
renaming operations. Neither answer is ideal.

But, there is another way, using a bit of Expression tree manipulation
you can build an ‘Or‘ expression dynamically while staying
strongly-typed. The code below achieves this.

[csharp] using System; using System.Linq; using System.Linq.Expressions;
using System.Collections.Generic;