如何检查集合是否包含集合

时间:2016-08-31 21:34:32

标签: c# linq

我有两个集合ProdList<Product, int>RuleList<Product, int>包含产品和计数列表。

如果RuleList所有项目都参与ProdList集合,我该怎么办? 我试过了

bool a= ProdList.All(x => RuleList.Contains(x)); 

但它不起作用。

1 个答案:

答案 0 :(得分:1)

它不起作用的原因是Contains方法使用项目的EqualsGetHashCode,如果不重写,则为object

解决方案:

  1. 覆盖您的对象的EqualsGetHashCode
  2. 使用Any代替Contains

    var result = ProdList.All(x => RuleList.Any(y => x.Product.Equals(y.Product) && 
                                                     x.IntValue == y.IntValue));
    
  3. 为对象的类型

  4. 实施自定义IEqualityComparer

    请注意,在所有这些选项中,您还必须注意比较Product类(可用的3个选项)