1

I want to remove from hs2 all items that appear in hs1.

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

For example

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

then I want hs2 to be:

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

I need something like:

hs2 = hs2.Remove('all items that exists in hs1...');
Iliar Turdushev
  • 4,935
  • 1
  • 10
  • 23
good_shabes
  • 161
  • 7
  • 3
    Does this answer your question? [Remove items from one list in another](https://stackoverflow.com/questions/2745544/remove-items-from-one-list-in-another) – funie200 Jul 22 '20 at 06:30

2 Answers2

3

You can use ExceptWith like below.

hs2.ExceptWith(hs1);

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

Karan
  • 12,059
  • 3
  • 24
  • 40
1

You can use RemoveWhere method.

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));
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197