score:2

Accepted answer

I think you want to use Expression.AndAlso (a short-circuiting AND) on the two predicate expressions in question to construct the body of the expression-tree.

var body = Expression.AndAlso(keyExists, valueCorresponds);
return Expression.Lambda<Func<Address, bool>>(body, dataFields);

EDIT: (If you want to stick with your existing technique)

My guess is that your And method is an extension-method from the LINQKit library. If so, note that this extension involves 'invoking' the right-hand side expression with the parameters of the first expression as part of producing the result. If this isn't acceptable to you (LINQ provider limitations, perhaps?), you can use the useful Expand extension that also comes with this library to 'inline' the invoked expression.

return Expression.Lambda<Func<Address, bool>>(keyExists, dataFields)
                 .And(Expression.Lambda<Func<Address, bool>>(valueCorresponds, dataFields))
                 .Expand();

But this is massive overkill in this case; my advice is to go with my first sample.


Related Articles