Predicate Builder

/// <summary>
	/// This class adds the ability to use the Or and And extension methods on any other expression.
	/// </summary>
	/// <remarks>Whilst extremely recursive in nature, this is the only way to add an OR to Linq at present without writing a huge number of things
	/// Source is here: http://www.albahari.com/nutshell/predicatebuilder.aspx
	/// But it's easy enough to write one, it is just a boolean expression chainer with and and or operations.
	/// </remarks>
	public static class PredicateBuilder
	{
		public static Expression<Func<T, bool>> True<T>() { return f => true; }
		public static Expression<Func<T, bool>> False<T>() { return f => false; }

		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.Cast<Expression>());
			return Expression.Lambda<Func<T, bool>>
				  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
		}

		public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
															 Expression<Func<T, bool>> expr2)
		{
			var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
			return Expression.Lambda<Func<T, bool>>
				  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
		}
	}

Revision #1
Created Sun, Sep 6, 2020 9:41 PM by Simon
Updated Sun, Sep 6, 2020 9:41 PM by Simon