score:3

Accepted answer

I think you want something like:

public static Expression<Func<TResult, bool>> GetPredicate<TKey>
    (Expression<Func<TResult, TKey>> selector, TResult input, object value)
{
    // Note: Move "early out" here so that bulk of method is less deeply nested.
    // Really? Why make this generic in TKey then?
    if (typeof(TKey) != typeof(string))
    {
        throw new Exception("Type not supported");
    }

    var parameter = Expression.Parameter("input");
    var invocation = Expression.Invoke(selector, input);
    var constant = Expression.Constant(value);
    var equality = Expression.Equal(invocation, constant);
    return Expression.Lambda<Func<TResult, bool>>(equality, parameter);
}

I'm not quite sure what kind of equality that will use, mind you - it's entirely possible it's going to use a reference equality operation, whereas I suspect you want value equality. You'll have to try it to see, being careful in tests due to string interning.

score:0

return p => (selector.Compile().Invoke(input) as string) == value

Related Articles