从 hashset 2 中删除出现在 hashset 中的所有项目

Remove all items that appeas in hashset1 from hashset2

我想从 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...');

您可以使用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));

您可以像下面那样使用 ExceptWith

hs2.ExceptWith(hs1);

ExceptWith : Removes all elements in the specified collection from the current HashSet object.