.NET Framework building a predicate of form field == value


Example

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:

  • IQueryable<T>, IEnumerable<T> to test the predicate.
  • entity framework or Linq to SQL to create a Where clause that tests the predicate.

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>>(
        expression,
        memberAccessor.Parameters);
    return predicate;
}

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

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