Filtering on template list with property name as string

前端 未结 4 1592
灰色年华
灰色年华 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:50

    You can use Reflection for retrieving the property value and you can use a simple switch statement upon the operator to perform the filtering:

    public IEnumerable ApplyFilter(string propertyName, EnumOperator op, object value)
    {
        foreach (T item in sourceList)
        {
            object propertyValue = GetPropertyValue(item, propertyName);
            if (ApplyOperator(item, propertyValue, op, value)
            {
                yield return item;
            }
        }
    }
    
    private object GetPropertyValue(object item, string propertyName)
    {
        PropertyInfo property = item.GetType().GetProperty(propertyName);
        //TODO handle null
        return property.GetValue();
    }
    
    private bool ApplyOperator(object propertyValue, EnumOperator op, object value)
    {
        switch (op)
        {
            case EnumOperator.Equals:
                return propertyValue.Equals(value);
            //TODO other operators
            default:
                throw new UnsupportedEnumException(op);
        }
    }
    

    (An optimization would be to look up the PropertyInfo once outside of the loop.)

提交回复
热议问题