与属性名作为字符串过滤的模板列表 [英] Filtering on template list with property name as string
问题描述
您好我要申请过滤器通用类。样本类如下:
Hi I have to apply filter on generic class. The sample class is as follows
public class Sample<T>
{
List<T> sourceList = new List<T>();
public void applyFilter(string propertyName , EnumOperator operator , object value)
{
}
}
在这里,我想使用LINQ或动态LINQ来实现过滤器,但我没有得到任何积极的方向来实现此功能。
Here I want to implement filter using linq or dynamic linq but am not getting any positive direction to implement this functionality.
请给我一些积极的方向,这样我可以实现这个功能。
Please give me some positive direction so that I can implement this functionality.
感谢。
推荐答案
我会建议返回一个过滤列表,而不是修改源,也是字符串经营者是一个C#的关键字,因此该方法的签名可能是
I would recommend returning an filtered list instead of modifying the source, and also the string "operator" is a C# keyword, so the signature of the method could be:
public List<T> ApplyFilter(string propertyName, EnumOperator operatorType, object value)
{
....
}
我的假设 EnumOperator
是枚举
有这样的价值观:
where I assume that the EnumOperator
is an enum
with values like this:
public enum EnumOperator
{
Equal,
NotEqual,
Bigger,
Smaller
}
和你有一些方法来检查,如果一个运营商的值通过或未能通过测试,沿着线的东西:
and that you have some way to check if for an operator a value passes or fails the test, something along the lines of:
public static class OperatorEvaluator
{
public static bool Evaluate(EnumOperator operatorType, object first, object second)
{
...
}
}
鉴于这种情况,你可以这样做:
Given that, you can do something like:
public List<T> ApplyFilter(string propertyName , EnumOperator operatorType, object value)
{
PropertyInfo pi = typeof(T).GetProperty(propertyName);
List<T> result = sourceList.Where(item => {
var propValue = pi.GetValue(item, null);
return OperatorEvaluator.Evaluate(operatorType, propValue, value);
}).ToList();
return result;
}
这是说,你总是可以使用LINQ的方法,而不是诉诸反射过滤几乎所有的东西。
That said, you can always use LINQ's methods to filter almost anything without resorting to reflection.
这篇关于与属性名作为字符串过滤的模板列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!