HashSet Iterating While Removing Items in C#

Viewed 33199

I have a hashset in C# that I'm removing from if a condition is met while iterating though the hashset and cannot do this using a foreach loop as below.

foreach (String hashVal in hashset) 
{
     if (hashVal == "somestring") 
     {
            hash.Remove("somestring");
     }
}

So, how can I remove elements while iterating?

6 Answers

For people who are looking for a way to process elements in a HashSet while removing them, I did it the following way

var set = new HashSet<int> {1, 2, 3};

while (set.Count > 0)
{
  var element = set.FirstOrDefault();
  Process(element);
  set.Remove(element);
}

there is a much simpler solution here.

var mySet = new HashSet<string>();
foreach(var val in mySet.ToArray() {
   Console.WriteLine(val);
   mySet.Remove(val);
}

.ToArray() already creates a copy for you. you can loop to your hearts content.

Related