创建动态谓词 – 将属性作为参数传递给函数

我正在尝试创建动态谓词,以便它可以用于过滤列表

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

我希望能够创建一个动态谓词,以便可以过滤List。 我得到一些条件,因为字符串值“>”,“ =”等。我有办法做到这一点吗?

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

用法可能是:

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

如何定义GetFilter? 以及如何在其中创建谓词?

 public Predicate GetFilter( Expression> property, T value, string condition) { switch (condition) { case ">=": return Expression.Lambda>( Expression.GreaterThanOrEqual( property.Body, Expression.Constant(value) ), property.Parameters ).Compile(); default: throw new NotSupportedException(); } } 

任何问题? 🙂