创建动态Predicates-传递属性设置为一个函数参数 [英] Creating Dynamic Predicates- passing in property to a function as parameter
本文介绍了创建动态Predicates-传递属性设置为一个函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建动态的谓词,以便它可以对过滤
公共类功能$ B名单被使用$ b {
公共串色{获取;集;}
公共字符串重量{获取;集;}
}
我希望能够创建一个动态断言,这样一个列表可以被过滤。我得到几个条件字符串值>,<,> =等有没有办法通过它我可以做到这一点。
公共谓词<特征>用getFilter(X属性,T值,字符串条件)//不知道什么X将是
{
开关(情况):
{
案> =:
返回新的谓词<特征>(性> =值)//或类似的东西
}
}
和使用情况可能是:
VAR filterConditions =用getFilter(X => X。重量,100,> =);
应如何用getFilter界定? ?以及如何创建内部谓词
解决方案
公共谓词<特征>用getFilter< T>(
表达式来; Func键<特征,T>>物业,
吨价,
串情况):
{
开关(条件)
{
案> =:
返回
Expression.Lambda<谓语<特征>>(
Expression.GreaterThanOrEqual(
property.Body,
Expression.Constant(值)
)
property.Parameters
).Compile();
默认:
抛出新NotSupportedException异常();
}
}
有问题吗? : - )
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?
解决方案
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? :-)
这篇关于创建动态Predicates-传递属性设置为一个函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文