Building a predicate of the form field == value
suggest changeTo build an expression like _ => _.Field == "VALUE" at runtime.
Given a member accessor _ => _.Field and a string value "VALUE", create an expression that tests whether that member equals the value.
The expression is suitable for:
IQueryable<T>andIEnumerable<T>, to test the predicate.- Entity Framework or LINQ to SQL, to create a
Whereclause that tests the predicate.
This method builds an Equal expression that tests whether 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();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents