C# 创建动态谓词-将属性作为参数传递给函数
我正在尝试创建动态谓词,以便可以对列表使用它进行筛选C# 创建动态谓词-将属性作为参数传递给函数,c#,dynamic,lambda,expression,predicates,C#,Dynamic,Lambda,Expression,Predicates,我正在尝试创建动态谓词,以便可以对列表使用它进行筛选 public class Feature { public string Color{get;set;} public string Weight{get;set;} } 我希望能够创建一个动态谓词,以便可以过滤列表。我得到的条件很少,比如字符串值“>”、“=”等等。有什么方法可以做到这一点吗 public Predicate<Feature> GetFilter(X property,T value, str
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
}
}
如何定义GetFilter?如何在其中创建谓词?公共谓词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();
}
}
表达式属性,
T值,
字符串条件)
{
开关(条件)
{
案例“>=”:
返回
Lambda(
表达式。大于或等于(
财产,身体,,
表达式.常量(值)
),
属性.参数
).Compile();
违约:
抛出新的NotSupportedException();
}
}
有问题吗?:-)
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();
}
}