c# - 如何在列表中(同时)应用多个过滤条件?

标签 c# linq generics design-patterns specification-pattern

我有以下 C# 代码和 .Net 4.0 框架。这是引用The Specification Pattern - by Jeff Perrin后创建的

GetProducts() 中,要使用的条件在方法内部定义(硬编码)。还有另一种名为 GetProductsBasedOnInputFilters() 的方法。在此方法中,规范列表作为方法的参数。

问题

在此方法中,将这些过滤器应用于产品列表的最佳方式是什么?

注意:我已经尝试在 foreach 循环中应用 FindAll 子句并将结果添加到 list。但这种逻辑是不正确的 - 只有满足所有 条件的项目才需要退回。

注意:productSpecifications 列表中的规范数量会因用户输入而异

注意:“Dynamically build LINQ filter for the Any() method?”中提到的方法似乎很有用。但是我不确定如何在这里使用这种方法,因为我正在处理 specifications 列表;不是 generic delegates

过滤方法

public static class ProductFilterHelper
{
    public static List<Product> GetProducts(List<Product> list)
    {
        double priceLimit = 100;

        //FIRST::
        //List<Product> selectedList =  list.FindAll(new OnSaleSpecification().IsSatisfiedBy);

        //SECOND::
        //AndSpecification<Product> spec = new AndSpecification<Product>(new OnSaleSpecificationForProduct(), new PriceGreaterThanSpecificationForProduct(priceLimit));
        //List<Product> selectedList = list.FindAll(spec.IsSatisfiedBy); 


        //THIRD:
        List<Product> selectedList = list.FindAll(new OnSaleSpecificationForProduct()
                                                       .And(new PriceGreaterThanSpecificationForProduct(priceLimit))
                                                       .And(new PriceGreaterThan105())
                                                       .IsSatisfiedBy
                                                  );

        return selectedList;
    }

    public static List<Product> GetProductsBasedOnInputFilters(List<Product> productList, List<Specification<Product>> productSpeifications)
    {
        List<Product> selectedList = new List<Product>();

        foreach (Specification<Product> specification in productSpeifications)
        {
            List<Product> currentList = productList.FindAll(specification.IsSatisfiedBy);

            if (currentList != null && currentList.Count > 0)
            {
                foreach (Product p in currentList)
                {
                    if (!selectedList.Contains(p))
                    {
                        selectedList.Add(p);
                    }
                }
            }
        }

        return selectedList;
    }        

}

客户端

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;

        List<Specification<Product>> specifications = new List<Specification<Product>>();
        specifications.Add(new OnSaleSpecificationForProduct());
        specifications.Add(new PriceGreaterThanSpecificationForProduct(priceLimit));
        specifications.Add(new PriceGreaterThan105());

        List<Product> selectedList = ProductFilterHelper.GetProductsBasedOnInputFilters(list, specifications);

        Console.ReadKey();
    }

}

抽象规范

public abstract class Specification<T>
{
    public abstract bool IsSatisfiedBy(T obj);

    public AndSpecification<T> And(Specification<T> specification)
    {
        return new AndSpecification<T>(this, specification);
    }

    public OrSpecification<T> Or(Specification<T> specification)
    {
        return new OrSpecification<T>(this, specification);
    }

    public NotSpecification<T> Not(Specification<T> specification)
    {
        return new NotSpecification<T>(this, specification);
    }
}

public abstract class CompositeSpecification<T> : Specification<T>
{
    protected readonly Specification<T> _leftSide;
    protected readonly Specification<T> _rightSide;

    public CompositeSpecification(Specification<T> leftSide, Specification<T> rightSide)
    {
        _leftSide = leftSide;
        _rightSide = rightSide;
    }
}

通用规范

public class AndSpecification<T> : CompositeSpecification<T>
{
    public AndSpecification(Specification<T> leftSide, Specification<T> rightSide)
        : base(leftSide, rightSide)
    {

    }

    public override bool IsSatisfiedBy(T obj)
    {
        return _leftSide.IsSatisfiedBy(obj) && _rightSide.IsSatisfiedBy(obj);
    }
}

public class OrSpecification<T> : CompositeSpecification<T>
{
    public OrSpecification(Specification<T> leftSide, Specification<T> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override bool IsSatisfiedBy(T obj)
    {
        return _leftSide.IsSatisfiedBy(obj) || _rightSide.IsSatisfiedBy(obj);
    }
}

public class NotSpecification<T> : CompositeSpecification<T>
{
    public NotSpecification(Specification<T> leftSide, Specification<T> rightSide)
        : base(leftSide, rightSide)
    {
    }

    public override bool IsSatisfiedBy(T obj)
    {
        return _leftSide.IsSatisfiedBy(obj) && !_rightSide.IsSatisfiedBy(obj);
    }
}

产品规范

public class OnSaleSpecificationForProduct : Specification<Product>
{
    public override bool IsSatisfiedBy(Product product)
    {
        return product.IsOnSale;
    }
}

public class PriceGreaterThanSpecificationForProduct : Specification<Product>
{
    private readonly double _price;
    public PriceGreaterThanSpecificationForProduct(double price)
    {
        _price = price;
    }

    public override bool IsSatisfiedBy(Product product)
    {
        return product.Price > _price;
    }
}

public class PriceGreaterThan105 : Specification<Product>
{

    public override bool IsSatisfiedBy(Product product)
    {
        return product.Price > 105;
    }
}

实体

public class Product
{
    private bool _isOnSale;
    private double _price = 0.0;

    public Product(bool isOnSale)
        : this(isOnSale, 0.0)
    {
        _isOnSale = isOnSale;
    }

    public Product(double price)
        : this(false, price)
    {
        _price = price;
    }

    public Product(bool isOnSale, double price)
    {
        _price = price;
        _isOnSale = isOnSale;
    }

    public bool IsOnSale
    {
        get { return _isOnSale; }
    }

    public double Price
    {
        get { return _price; }
    }
}

引用文献

  1. The Specification Pattern - by Jeff Perrin
  2. Fluent interfaces and Method Chaining in C#
  3. Avoid to browse a list multiple time with linq, with dynamic conditions (filter)
  4. Dynamically build LINQ filter for the Any() method?

最佳答案

您可以执行以下操作之一:

  • 通过将 Where 调用堆叠在一起来组合过滤器,就像@Lijo 的回答一样

  • 检查每个项目的所有规范:

    return productList
      .Where(p => specifications.All(ps => ps.IsSatisfiedBy(p))
      .ToList()
    
  • 创建一个接受多个子项而不是两个子项的复合“And”规范:

    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));
        }
      }
    

然后你可以这样做:

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

关于c# - 如何在列表中(同时)应用多个过滤条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21384357/

相关文章:

javascript - 为什么我的正则表达式在 .NET 中有效,但在 Javascript 中无效?

C# IList更新问题

c# - 如何创建 .rdlc 文件?

java - 内联扩展通用抽象 Template 类

generics - 我可以在 Rust 中使这个断言通用吗?

c# - 使用与创建类不同的泛型类型调用构造函数

c# - 覆盖 SpecFlow 中的步骤声明?

c# - 重新排序序列的最简单方法

c# - 使用Linq检查List <List <int> []>是否包含值

linq - LINQ OrderBy不订购..什么都没有改变..为什么?