How to combine conditions dynamically?

大城市里の小女人 提交于 2019-11-29 05:20:23

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!