我正在尝试创建动态谓词,以便它可以用于过滤列表
public class Feature
{
public string Color{get;set;}
public string Weight{get;set;}
}
我希望能够创建一个动态谓词,以便可以过滤列表。我得到的条件很少,如字符串值“>”、“<”、“>=”等。有什么方法可以做到这一点吗?
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
}
}
用法可能是:
var filterConditions=GetFilter(x=>x.Weight,100,">=");
GetFilter 应该如何定义?以及如何在其中创建谓词?
最佳答案
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();
}
}
有什么问题吗? :-)
关于c# - 创建动态谓词 - 将属性作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431617/