I need to create a Expression<Func<T, bool>>, but all I have is a LambaExpression of the property to compare and the value to use for the comparison.
This is what the predicate would look like if I hard code it, and this is what I need to achieve but don't know how.
string comparisonValue = "something";
Expression<Func<Person, bool>> predicate = person => person.Name == comparisonValue;
I have the following:
LambdaExpression expression = PropertyExpression<Person>(t => t.Name);
Is there a way to generate the hard coded predicate like the above with just a property LambdaExpression and the value to compare?
I've tried using LambdaExpression.Equal(), but cannot get it to work.
You can implement this as follows.
Expression<Func<TSource, bool>> EqualToExpression<TSource, TValue>(
Expression<Func<TSource, TValue>> selectValue, TValue targetValue)
{
return Expression.Lambda<Func<TSource, bool>>(
Expression.Equal(
selectValue.Body,
Expression.Constant(targetValue)),
selectValue.Parameters);
}
Use it as follows.
Expression<Func<Person, string>> selectName = p => p.Name;
Expression<Func<Person, bool>> compareName = EqualToExpression(selectName, "John");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With