IQueryable.Where
requires an Expression<Func<T, bool>>
, so that will be the thing we need to build. As we want to integrate something from another expression (a Expression<Func<T, string>>
), we have to build the expression “by hand”.
So in the end, we want to call LambdaExpression.Lambda<Func<T, bool>>(…)
to get our expression for Where
, but we need to fill in the expression body:
// first, we reuse the parameter from the `keySelector` expression
ParameterExpression param = keySelector.Parameters[0];
// The body is now just an equality comparison of the `keySelector`
// body, and the constant `filterValue`
Expression body = Expression.Equal(keySelector.Body, Expression.Constant(filterValue));
// now we just need to create a lambda expression for that body with the
// saved parameter and it’s all done:
queryable = queryable.Where(Expression.Lambda<Func<T, bool>>(body, param));