代码
public class LamdbaEx<T>
{
public Expression<Func<T, bool>> Lamdba { get; set; }
public LamdbaEx()
{
Lamdba = x => true;
}
public void And(Expression<Func<T, bool>> second)
{
Lamdba = Compose(second, Expression.AndAlso);
}
public void Or(Expression<Func<T, bool>> second)
{
Lamdba = Compose(second, Expression.OrElse);
}
public Expression<T> Compose<T>(Expression<T> second, Func<Expression, Expression, Expression> merge)
{
var map = Lamdba.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda<T>(merge(Lamdba.Body, secondBody), Lamdba.Parameters);
}
}
public class ParameterRebinder : ExpressionVisitor
{
readonly Dictionary<ParameterExpression, ParameterExpression> map;
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
使用
var la=new LamdbaEx<T>();
if(1==1){
la.And(x=>1==1);
}
if(1==2){
la.Or(x=>1==1);
}
var l=list.Where(la.Lamdba).ToList();