using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace AsbCloudInfrastructure
{
#nullable enable
///
/// stolen from https://github.com/lotosbin/BinbinPredicateBuilder
///
public static class PredicateBuilder
{
///
/// Combines the first predicate with the second using the logical "and".
///
public static Expression> And(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.AndAlso);
}
///
/// Combines the first predicate with the second using the logical "or".
///
public static Expression> Or(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.OrElse);
}
///
/// Negates the predicate.
///
public static Expression> Not(this Expression> expression)
{
var negated = Expression.Not(expression.Body);
return Expression.Lambda>(negated, expression.Parameters);
}
private static Expression Compose(this Expression first, Expression second, Func merge)
{
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
var tryReplaceParametr = (Expression node) =>
{
if (node is ParameterExpression parameter)
if (map.TryGetValue(parameter, out ParameterExpression? replacement))
return replacement;
return node;
};
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
}
class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary map;
private ParameterRebinder(Dictionary map)
{
this.map = map;
}
public static Expression ReplaceParameters(Dictionary map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression parametr)
{
if (map.TryGetValue(parametr, out ParameterExpression? replacement))
parametr = replacement;
return parametr;
}
}
}
}
#nullable disable