How to apply multiple filter conditions (simultaneously) on a list?

梦想的初衷 提交于 2019-12-03 09:49:46

You can do one of several things:

  • Combine the filters by stacking Where invocations on top of each other, like in @Lijo's answer

  • Check all specifications on each item:

    return productList
      .Where(p => specifications.All(ps => ps.IsSatisfiedBy(p))
      .ToList()
    
  • Create a composite 'And' specification that accepts multiple children instead of just two:

    public class AndSpecification<T> : ISpecification<T>
    {
        private ISpecification<T>[] _components;
    
        public AndSpecification(ISpecification<T>[] components) 
        {
          _components = components;
        }
    
        public bool IsSatisfiedBy(T item) 
        {
          return components.All(c => c.IsSatisfiedBy(item));
        }
      }
    

Then you could do:

var allFiltersSpecification = new AndSpecification(specifications)
return productList.Where(allFiltersSpecification.IsSatisfiedBy);

Following code works... Suggestions are welcome.

 public static List<Product> GetProductsBasedOnInputFilters(List<Product> productList, List<Specification<Product>> productSpecifications)
 {
            IEnumerable<Product> selectedList = productList;
            foreach (Specification<Product> specification in productSpecifications)
            {
                selectedList = selectedList.Where(specification.IsSatisfiedBy);
            }
            return selectedList.ToList();
 }

It is worth to take a look at the following too..

  1. Expression Tree Basics
  2. Generating Dynamic Methods with Expression Trees in Visual Studio 2010
  3. Dynamically Composing Expression Predicates
  4. How to combine conditions dynamically?
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!