How do I dynamically construct a predicate method from an expression tree?

∥☆過路亽.° 提交于 2019-12-04 19:29:39

to do this for a PagedCollectionView, you need to have a Predicate. So it looks like:

private Predicate<object> ConvertExpressionToPredicate(Expression<Func<object, bool>> exp)
{
  Func<object, bool> func = exp.Compile();
  Predicate<object> predicate = new Predicate<object>(func);
  //Predicate<object> predicate = t => func(t);     // also works
  //Predicate<object> predicate = func.Invoke;      // also works
  return predicate;
}

and build the expression:

private Expression<Func<object, bool>> BuildFilterExpression()
{
  ...snip...
  var predicate = PredicateBuilder.True<object>();
  if (ViewMineOnly)
  {
    predicate = predicate.And(r => ((Rating)r).Assigned_To.Trim().ToUpper() == sUserNameFilter || ((Rating)r).Assigned_To.Trim().ToUpper() == "UNCLAIMED");
  }
  if (ViewStarOnly)
  {
    predicate = predicate.And(r => ((Rating)r).Star.HasValue && ((Rating)r).Star.Value > 0);
  }
  if (FilterOnOrder)
  {
    predicate = predicate.And(r => ((Rating)r).ShipmentInvoice.Trim().ToUpper().StartsWith(sOrderNumberFilter));
  }
  if (ViewDueOnly)
  {
    predicate = predicate.And(r => ((Rating)r).SettlementDueDate <= ThisThursday);
  }
  return predicate;
}

and then set the filter:

Ratings.Filter = ConvertExpressionToPredicate(BuildFilterExpression());

I faced the same problem. I had 3 criteria. What I did is the following :

  • One method to validate each criteria
  • One method to validate the object

The code looked quite clean and it was easy to maintain.

Ratings.Filter = new predicate<objects>(validateObject);

private bool validateObject(object o)
{
  return validateFirstCriteria(o) && 
         validateSecondCriteria(o) && 
         validateThirdCriteria(o);
}

private bool validateFirstObject(object o)
{
  if (ViewMineOnly)
  {
    Rating r = o as Rating;
    if (o != null)
    {
      return  (r.Star.HasValue && r.Star.Value > 0);
    }
  }
  return false;
}
private bool validateSecondObject(object o)
{
  if (ViewStarOnly)
  {
    Rating r = o as Rating;
    if (o != null)
    {
      return sUserNameFilter == r.Assigned_To;
    }
  }
  return false;
}
private bool validateThirdObject(object o)
{
  if (FilterOnOrder)
  {
    Rating r = o as Rating;
    if (o != null)
    {
      return r.ShipmentInvoice.StartsWith(sOrderNumberFilter);
    }
  }
  return false;
}

EDIT

If you want to stuck to Expression trees. You could take a look here : http://msdn.microsoft.com/en-us/library/bb882536.aspx

You can convert the expression tree to a lambda expression and then compile the lambda expression. After then you can use it as a method. Exemple :

        // The expression tree to execute.
        BinaryExpression be = Expression.Power(Expression.Constant(2D), Expression.Constant(3D));

        // Create a lambda expression.
        Expression<Func<double>> le = Expression.Lambda<Func<double>>(be);

        // Compile the lambda expression.
        Func<double> compiledExpression = le.Compile();

        // Execute the lambda expression.
        double result = compiledExpression();

        // Display the result.
        Console.WriteLine(result);

        // This code produces the following output:
        // 8
tobewan

Thanks to Benjamin's hints and this post -> How to convert Func<T, bool> to Predicate<T>? I figured it out.
The essence is:


private static Predicate<T> ConvertExpressionToPredicate(Expression<Func<T, bool>> exp)
{
  Func<T, bool> func = exp.Compile();
  Predicate<T> predicate = new Predicate<T>(func);
  //Predicate<T> predicate = t => func(t);     // also works
  //Predicate<T> predicate = func.Invoke;      // also works
  return predicate;
}

This will compile the expression tree to a single function and return a predicate to call the function.
In use, it looks like:

private static bool ViewStarOnly;
private static bool LongNameOnly;
static void Main(string[] args)
{
  List<Dabble> data = GetSomeStuff();
  ViewStarOnly = true;
  LongNameOnly = true;
  Expression<Func<Dabble, bool>> exp = BuildFilterExpression();
  List<Dabble> filtered = data.FindAll(ConvertExpressionToPredicate(exp));
  PrintSomeStuff(filtered);
}

private static Predicate<Dabble> ConvertExpressionToPredicate(Expression<Func<Dabble, bool>> exp)
{
  Func<Dabble, bool> func = exp.Compile();
  Predicate<Dabble> predicate = new Predicate<Dabble>(func);
  //Predicate<Dabble> predicate = t => func(t);     // also works
  //Predicate<Dabble> predicate = func.Invoke;      // also works
  return predicate;
}

private static Expression<Func<Dabble, bool>> BuildFilterExpression()
{
  var predicate = PredicateBuilder.True<Dabble>();
  if (ViewStarOnly)
  {
    predicate = predicate.And(r => r.Star.HasValue && r.Star.Value > 0);
  }
  if (LongNameOnly)
  {
    predicate = predicate.And(r => r.Name.Length > 3);
  }
  return predicate;
}

Thanks!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!