Another possible solution to this, especially when someone does not want to use an external library, is to use expression trees.
Add the following expression extension:
public static Expression<Func<T, bool>> Or<T>( this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters); return Expression.Lambda<Func<T, bool>>( Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); }
As an example, suppose you have a Container object that has a nested InnerContainer object with two Name and Id properties. Then you can use it as follows:
Expression<Func<Container, bool>> whereQuery = c => c.InnerContainer.Name == "Name1"; whereQuery = whereQuery.Or(c => c.InnerContainer.Name == "Name2"); whereQuery = whereQuery.Or(c => c.InnerContainer.Id == 0); var result = query .Where(whereQuery) .ToList();
Materializing such a query will result in the following SQL:
SELECT [x].[Id], [x].[InnerContainerId] FROM [Containers] AS [x] LEFT JOIN [InnerContainer] AS [x.InnerContainer] ON [x].[InnerContainerId] = [x.InnerContainer].[Id] WHERE [x.InnerContainer].[Name] IN (N'Name1', N'Name2') OR ([x].[InnerContainerId] = 0)
This way you can keep lambdas in the collection and scroll through them.
source share