Hi I have to apply filter on generic class. The sample class is as follows
public class Sample
{
List sourceList = new List();
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 ApplyFilter(string propertyName, EnumOperator operatorType, object value)
{
....
}
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 ApplyFilter(string propertyName , EnumOperator operatorType, object value)
{
PropertyInfo pi = typeof(T).GetProperty(propertyName);
List result = sourceList.Where(item => {
var propValue = pi.GetValue(item, null);
return OperatorEvaluator.Evaluate(operatorType, propValue, value);
}).ToList();
return result;
}
That said, you can always use LINQ's methods to filter almost anything without resorting to reflection.