【问题标题】:Remove all items that appeas in hashset1 from hashset2 [duplicate]从哈希集中删除哈希集中出现的所有项目[重复]
【发布时间】:2020-07-22 06:26:51
【问题描述】:

我想从hs2 中删除所有出现在hs1 中的项目。

HashSet<string> hs1 = ...;
HashSet<string> hs2 = ...;

例如

hs1 = {"a","b","c"}
hs2 = {"a","d","e","f","b"}

那么我希望hs2 成为:

hs2 = {"d","e","f"}

我需要类似的东西:

hs2 = hs2.Remove('all items that exists in hs1...');

【问题讨论】:

标签: c# hashset


【解决方案1】:

您可以使用ExceptWith,如下所示。

hs2.ExceptWith(hs1);

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

【讨论】:

    【解决方案2】:

    你可以使用RemoveWhere方法。

    HashSet<string> hs1 = new HashSet<string>() { "a", "b", "c" };
    HashSet<string> hs2 = new HashSet<string>() { "a", "d", "e", "f", "b" };
    
    hs2.RemoveWhere(x => hs1.Contains(x));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2015-04-25
      • 2018-07-27
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多