building a predicate of form field value

suggest change

To build up an expression like _ => _.Field == "VALUE" at runtime.

Given a predicate _ => _.Field and a string value "VALUE", create an expression that tests whether or not the predicate is true.

The expression is suitable for:

This method will build an appropriate Equal expression that tests whether or not Field equals "VALUE".

public static Expression<Func<T, bool>> BuildEqualPredicate<T>(
    Expression<Func<T, string>> memberAccessor,
    string term)
    var toString = Expression.Convert(Expression.Constant(term), typeof(string));
    Expression expression = Expression.Equal(memberAccessor.Body, toString);
    var predicate = Expression.Lambda<Func<T, bool>>(
    return predicate;

The predicate can be used by including the predicate in a Where extension method.

var predicate = PredicateExtensions.BuildEqualPredicate<Entity>(
    _ => _.Field,
var results = context.Entity.Where(predicate).ToList();

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents