I\'d like to merge the following Expressions:
// example class
class Order
{
List Lines
}
class OrderLine { }
Expression
This extension works:
public static class Utility
{
public static Expression Compose(this Expression first, Expression second, Func merge)
{
// build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
}
public static Expression> And(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.And);
}
public static Expression> Or(this Expression> first, Expression> second)
{
return first.Compose(second, Expression.Or);
}
}
Sample using:
Expression> filter1 = p => a.ProductId == 1;
Expression> filter2 = p => a.Text.StartWith("test");
Expression> filterCombined = filter1.And(filter2);