Filtering collection with LINQ

后端 未结 4 1191
醉话见心
醉话见心 2021-02-02 02:19

Let\'s say we have a collection of Person objects

class Person 
{
     public string PersonName {get;set;}
     public string PersonAddress {get;set;}    
}
         


        
4条回答
  •  隐瞒了意图╮
    2021-02-02 02:53

    I would add a method to the Filter class to check if the filter is satisfied:

    class Filter 
    {
        public string FieldName {get;set;}
        public string FilterString {get;set;}
    
        public bool IsSatisfied(object o)
        { return o.GetType().GetProperty(FieldName).GetValue(o, null) as string == FilterString;
    }
    

    You can then use it like this:

    var filtered_list = personsList.Where(p => userFilters.Any(f => f.IsSatisfied(p)));
    

提交回复
热议问题