Filtering on template list with property name as string

前端 未结 4 1604
灰色年华
灰色年华 2021-01-16 06:26

Hi I have to apply filter on generic class. The sample class is as follows

public class Sample
{
    List sourceList = new List();         


        
4条回答
  •  死守一世寂寞
    2021-01-16 06:43

    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.

提交回复
热议问题