1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| using System; using System.Collections.Generic; using System.Linq.Expressions;
namespace Masuit.Tools.Linq;
public static class LinqExtension { public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right) { return CombineLambdas(left, right, ExpressionType.AndAlso); }
public static Expression<Func<T, bool>> AndIf<T>(this Expression<Func<T, bool>> left, bool condition, Expression<Func<T, bool>> right) { return condition ? CombineLambdas(left, right, ExpressionType.AndAlso) : left; }
public static Expression<Func<T, bool>> AndIf<T>(this Expression<Func<T, bool>> left, Func<bool> condition, Expression<Func<T, bool>> right) { return condition() ? CombineLambdas(left, right, ExpressionType.AndAlso) : left; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right) { return CombineLambdas(left, right, ExpressionType.OrElse); }
public static Expression<Func<T, bool>> OrIf<T>(this Expression<Func<T, bool>> left, bool condition, Expression<Func<T, bool>> right) { return condition ? CombineLambdas(left, right, ExpressionType.OrElse) : left; }
public static Expression<Func<T, bool>> OrIf<T>(this Expression<Func<T, bool>> left, Func<bool> condition, Expression<Func<T, bool>> right) { return condition() ? CombineLambdas(left, right, ExpressionType.OrElse) : left; }
private static Expression<Func<T, bool>> CombineLambdas<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right, ExpressionType expressionType) { var visitor = new SubstituteParameterVisitor { Sub = { [right.Parameters[0]] = left.Parameters[0] } };
Expression body = Expression.MakeBinary(expressionType, left.Body, visitor.Visit(right.Body)); return Expression.Lambda<Func<T, bool>>(body, left.Parameters[0]); } }
internal class SubstituteParameterVisitor : ExpressionVisitor { public Dictionary<Expression, Expression> Sub = new();
protected override Expression VisitParameter(ParameterExpression node) { return Sub.TryGetValue(node, out var newValue) ? newValue : node; } }
|