ven*_*kod 7 c# lambda expression dynamic predicates
我正在尝试创建动态谓词,以便它可以用于过滤列表
public class Feature
{
public string Color{get;set;}
public string Weight{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够创建一个动态谓词,以便可以过滤List.我得到一些条件,因为字符串值">","<","> ="等.有什么方法可以做到这一点?
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
}
}
Run Code Online (Sandbox Code Playgroud)
用法可能是:
var filterConditions=GetFilter(x=>x.Weight,100,">=");
Run Code Online (Sandbox Code Playgroud)
如何定义GetFilter?以及如何在其中创建谓词?
dtb*_*dtb 14
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();
}
}
Run Code Online (Sandbox Code Playgroud)
任何问题?:-)
| 归档时间: |
|
| 查看次数: |
4376 次 |
| 最近记录: |