Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Dynamic Predicates- passing in property to a function as parameter

I am trying to create dynamic predicate so that it can be used against a list for filtering

 public class Feature
 {
   public string Color{get;set;}
   public string Weight{get;set;}
 }

I want to be able to create a dynamic predicate so that a List can be filtered. I get few conditions as string values ">","<",">=" etc. Is there a way by which I can do this?

public Predicate<Feature> GetFilter(X property,T value, string condition) //no clue what X will be
 {
            switch(condition)
            {
              case ">=":
               return new Predicate<Feature>(property >= value)//or something similar
            }               
 }

and the usage could be:

 var filterConditions=GetFilter(x=>x.Weight,100,">=");

How should the GetFilter be defined? and how to create the predicate inside that?

like image 692
venkod Avatar asked Aug 07 '10 18:08

venkod


1 Answers

public Predicate<Feature> GetFilter<T>(
    Expression<Func<Feature, T>> property,
    T value,
    string condition)
{
    switch (condition)
    {
    case ">=":
        return
            Expression.Lambda<Predicate<Feature>>(
                Expression.GreaterThanOrEqual(
                    property.Body,
                    Expression.Constant(value)
                ),
                property.Parameters
            ).Compile();

    default:
        throw new NotSupportedException();
    }
}

Any questions? :-)

like image 64
dtb Avatar answered Nov 06 '22 22:11

dtb