Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Expression<Func<T, bool>> predicate with just LambaExpression and comparison value

Tags:

c#

.net

lambda

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.

like image 576
Steven Yates Avatar asked Mar 16 '26 09:03

Steven Yates


1 Answers

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");
like image 68
Timothy Shields Avatar answered Mar 18 '26 22:03

Timothy Shields



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!