C# in a Nutshell has a free class called PredicateBuilder which constructs LINQ predicates piece by piece available here. Here\'s an extract of the method which adds a new
Let's say you have:
Expression<Func<Person, bool>> isAdult = p1 => p1.Age >= 18;
// I've given the parameter a different name to allow you to differentiate.
Expression<Func<Person, bool>> isMale = p2 => p2.Gender == "Male";
And then combine them with PredicateBuilder
var isAdultMale = isAdult.And(isMale);
What PredicateBuilder
produces is an expression that looks like this:
// Invoke has no direct equivalent in C# lambda expressions.
p1 => p1.Age >= 18 && Invoke(p2 => p2.Gender == "Male", p1)
As you can see:
And
s the first expression's body and this InvocationExpression
together to produce the body of the resulting lambda.The idea is that the LINQ provider should be able to understand the semantics of this operation and take a sensible course of action (e.g. generate SQL like WHERE age >= 18 AND gender = 'Male'
).
Often though, providers have problems with InvocationExpression
s, because of the obvious complications of processing a 'nested expression-call inside an expression.'
To get around this, LINQKit also provides the Expand
helper. This essentially 'inlines' the invocation call smartly by replacing the call with the body of the nested expression, substituting uses of the nested expression's parameters appropriately (in this case, replacing p2
with p1
). This should produce something like:
p1 => p1.Age >= 18 && p1.Gender == "Male"
Note that this how you would have manually combined those predicates if you'd done it yourself in a lambda. But with LINQKit around, you can get these predicates from independent sources and easily combine them: