|
| 1 | +using AutSoft.Linq.Expressions.ExpressionVisitors; |
| 2 | + |
| 3 | +using System.Linq.Expressions; |
| 4 | + |
| 5 | +namespace AutSoft.Linq.Expressions; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Extension methods for <see cref="Expression{T}"/> with extended functionality for logical operators |
| 9 | +/// </summary> |
| 10 | +public static class LogicalOperatorExtensions |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Performing an AND operation on two <see cref="Expression{T}"/> |
| 14 | + /// </summary> |
| 15 | + /// <typeparam name="T">Type of input paramter of the <see cref="Expression{T}"/>'s function</typeparam> |
| 16 | + /// <param name="leftExp">The left sided <see cref="Expression{T}"/> of AND operation</param> |
| 17 | + /// <param name="rightExp">The right sided <see cref="Expression{T}"/> of AND operation</param> |
| 18 | + /// <returns>The result <see cref="Expression{T}"/> after the AND operation</returns> |
| 19 | + public static Expression<Func<T, bool>> And<T>( |
| 20 | + this Expression<Func<T, bool>> leftExp, |
| 21 | + Expression<Func<T, bool>> rightExp) |
| 22 | + { |
| 23 | + var visitor = new ParameterUpdateVisitor(rightExp.Parameters[0], leftExp.Parameters[0]); |
| 24 | + rightExp = (Expression<Func<T, bool>>)visitor.Visit(rightExp); |
| 25 | + |
| 26 | + var binExp = Expression.And(leftExp.Body, rightExp.Body); |
| 27 | + return Expression.Lambda<Func<T, bool>>(binExp, rightExp.Parameters); |
| 28 | + } |
| 29 | + |
| 30 | + /// <summary> |
| 31 | + /// Performing an OR operation on two <see cref="Expression{T}"/> |
| 32 | + /// </summary> |
| 33 | + /// <typeparam name="T">Type of input paramter of the <see cref="Expression{T}"/>'s function</typeparam> |
| 34 | + /// <param name="leftExp">The left sided <see cref="Expression{T}"/> of OR operation</param> |
| 35 | + /// <param name="rightExp">The right sided <see cref="Expression{T}"/> of OR operation</param> |
| 36 | + /// <returns>The result <see cref="Expression{T}"/> after the OR operation</returns> |
| 37 | + public static Expression<Func<T, bool>> Or<T>( |
| 38 | + this Expression<Func<T, bool>> leftExp, |
| 39 | + Expression<Func<T, bool>> rightExp) |
| 40 | + { |
| 41 | + var visitor = new ParameterUpdateVisitor(rightExp.Parameters[0], leftExp.Parameters[0]); |
| 42 | + rightExp = (Expression<Func<T, bool>>)visitor.Visit(rightExp); |
| 43 | + |
| 44 | + var binExp = Expression.Or(leftExp.Body, rightExp.Body); |
| 45 | + return Expression.Lambda<Func<T, bool>>(binExp, rightExp.Parameters); |
| 46 | + } |
| 47 | +} |
0 commit comments