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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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();


Got any .NET Framework Question?