34 lines
1.4 KiB
C#
34 lines
1.4 KiB
C#
namespace TrackCenter.Domain;
|
|
|
|
public static class ExpressionExtensions
|
|
{
|
|
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
|
|
{
|
|
Expression right = new RebindParameterVisitor(expr2.Parameters[0], expr1.Parameters[0]).Visit(expr2.Body);
|
|
return Expression.Lambda<Func<T, bool>>((Expression) Expression.AndAlso(expr1.Body, right), (IEnumerable<ParameterExpression>) expr1.Parameters);
|
|
}
|
|
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
|
|
Expression<Func<T, bool>> expr2)
|
|
{
|
|
var expr2Body = new RebindParameterVisitor(expr2.Parameters[0], expr1.Parameters[0]).Visit(expr2.Body);
|
|
return Expression.Lambda<Func<T, bool>>(Expression.OrElse(expr1.Body, expr2Body), expr1.Parameters);
|
|
}
|
|
|
|
private class RebindParameterVisitor : ExpressionVisitor
|
|
{
|
|
private readonly ParameterExpression _oldParameter;
|
|
private readonly ParameterExpression _newParameter;
|
|
|
|
public RebindParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
|
|
{
|
|
_oldParameter = oldParameter;
|
|
_newParameter = newParameter;
|
|
}
|
|
|
|
protected override Expression VisitParameter(ParameterExpression node)
|
|
{
|
|
return node == _oldParameter ? _newParameter : base.VisitParameter(node);
|
|
}
|
|
}
|
|
}
|