Dynamically Composing Expression Predicates

Very nice description how to dynamically create expression predicates. I pass it to my blog to have quick reference.

Reference page

PredicateBuilder Source Code

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
 
public static class PredicateBuilder
{
  public static Expression<Func> True ()  { return f => true;  }
  public static Expression<Func> False () { return f => false; }
 
  public static Expression<Func> Or (this Expression<Func> expr1,
                                                      Expression<Func> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
    return Expression.Lambda<Func>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }
 
  public static Expression<Func> And (this Expression<Func> expr1,
                                                       Expression<Func> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
    return Expression.Lambda<Func>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

Using PredicateBuilder

I want to dynamically create the following predicate


p => p.Price > 100 &&
     p.Price < 1000 &&
     (p.Description.Contains ("foo") || p.Description.Contains ("far"))

so I can do it in this way…

var inner = PredicateBuilder.False();
inner = inner.Or (p => p.Description.Contains ("foo"));
inner = inner.Or (p => p.Description.Contains ("far"));

var outer = PredicateBuilder.True();
outer = outer.And (p => p.Price > 100);
outer = outer.And (p => p.Price < 1000);
outer = outer.And (inner);

Notice that with the inner expression, we start with PredicateBuilder.False (because we’re using the Or operator). With the outer expression, however, we start with PredicateBuilder.True (because we’re using the And operator).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s