这里最简单的做法是Expression.Invoke,例如:
public static Expression<Func<T, bool>> AndAlso<T>(
Expression<Func<T, bool>> x, Expression<Func<T, bool>> y)
{
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(x.Body, Expression.Invoke(y, x.Parameters)),
x.Parameters);
}
这适用于 LINQ-to-Objects 和 LINQ-to-SQL,但不受 EF 支持。遗憾的是,对于 EF,您需要使用访问者来重写树。
使用来自:Combining two lambda expressions in c#的代码
public static Expression<Func<T, bool>> AndAlso<T>(
Expression<Func<T, bool>> x, Expression<Func<T, bool>> y)
{
var newY = new ExpressionRewriter().Subst(y.Parameters[0], x.Parameters[0]).Inline().Apply(y.Body);
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(x.Body, newY),
x.Parameters);
}
或者在 .NET 4.0 中,使用ExpressionVisitor:
class ParameterVisitor : ExpressionVisitor
{
private readonly ReadOnlyCollection<ParameterExpression> from, to;
public ParameterVisitor(
ReadOnlyCollection<ParameterExpression> from,
ReadOnlyCollection<ParameterExpression> to)
{
if(from == null) throw new ArgumentNullException("from");
if(to == null) throw new ArgumentNullException("to");
if(from.Count != to.Count) throw new InvalidOperationException(
"Parameter lengths must match");
this.from = from;
this.to = to;
}
protected override Expression VisitParameter(ParameterExpression node)
{
for (int i = 0; i < from.Count; i++)
{
if (node == from[i]) return to[i];
}
return node;
}
}
public static Expression<Func<T, bool>> AndAlso<T>(
Expression<Func<T, bool>> x, Expression<Func<T, bool>> y)
{
var newY = new ParameterVisitor(y.Parameters, x.Parameters)
.VisitAndConvert(y.Body, "AndAlso");
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(x.Body, newY),
x.Parameters);
}