How to combine conditions dynamically?

后端 未结 1 1867
挽巷
挽巷 2020-12-17 06:42

This question is an enhancement to the already answered question How to apply multiple filter conditions (simultaneously) on a list?

In the above mentioned question

相关标签:
1条回答
  • 2020-12-17 06:54

    By looking at the code you provided, it seems to me that your logic for combining filters is sound. The problem is the List<Specification<T>>. By having compound specification in place, you can combine them and only pass a Specification<T> (which would be a CompositeSpecification<T>):

    class Program
    {
    
        static void Main(string[] args)
        {
    
            List<Product> list = new List<Product>();
    
            Product p1 = new Product(false, 99);
            Product p2 = new Product(true, 99);
            Product p3 = new Product(true, 101);
            Product p4 = new Product(true, 110);
            Product p5 = new Product(false, 110);
    
            list.Add(p1);
            list.Add(p2);
            list.Add(p3);
            list.Add(p4);
            list.Add(p5);
    
            double priceLimit = 100;
    
             var specification =
                 new OnSaleSpecificationForProduct()
                     .And(new PriceGreaterThanSpecificationForProduct(priceLimit)
                                  .Or(new PriceGreaterThan105()));
    
            List<Product> selectedList = ProductFilterHelper.GetProductsBasedOnInputFilters(list, specification);
    
            Console.ReadKey();
        }
    
    }
    

    And your filtering method becomes:

     public static List<Product> GetProductsUisngDynamicFilters(List<Product> productList, Specification<Product> productSpecification)
        {
            return productList.Where(p => productSpecification.IsSatisfiedBy(p))
                              .ToList();
        }
    

    As a side note, you should consider moving the Or, And and Not method from the abstract Specification<T> to an extension method. And perhaps use interfaces instead.

    0 讨论(0)
提交回复
热议问题