Search code examples
c#dynamiclambdaexpressionpredicates

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?


Solution

  • 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? :-)