【问题标题】:Compare two hashsets?比较两个哈希集?
【发布时间】:2012-05-17 12:41:01
【问题描述】:

我有两个这样的哈希集:

HashSet<string> log1 = new HashSet<string>(File.ReadLines("log1.txt"));
HashSet<string> log2 = searcher(term);

如何比较两者?

我想确保log2 不包含来自log1 的任何条目。换句话说,我想删除 log1log2 中的所有(如果有的话)项目。

【问题讨论】:

  • 遍历 log1 中的每个元素并将它们与 log2 中的每个元素进行比较,这就是我的做法。尽管我不确定您将如何访问单个元素。我猜你可能能够为它构造一个foreach(log1中的字符串s)?注意:我从来没有使用过 HashSet 类型,我猜

标签: c#


【解决方案1】:

要从log2 中删除log1 中的所有项目,您可以使用HashSet<T>.ExceptWith Method

log2.ExceptWith(log1);

或者,您可以创建一个新的HashSet<T>,而无需使用Enumerable.Except Extension Method 修改两个原始集:

HashSet<string> log3 = new HashSet<string>(log2.Except(log1));

【讨论】:

    【解决方案2】:

    使用 LINQ:

    log1.Intersect(log2).Any()
    

    请参阅 MSDN 上的 IntersectExcept

    【讨论】:

    • @RoyiNamir - Any() 更好。
    • @RoyiNamir 如果您需要检查罐子里是否有硬币,您不必数,而是检查是否存在?
    【解决方案3】:

    你见过ExceptWith函数吗?

    从当前 HashSet 对象中移除指定集合中的所有元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2016-09-05
      • 2016-09-13
      相关资源
      最近更新 更多