HashSet Iterating While Removing Items in C

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

http://msdn.microsoft.com/en-us/library/bb361254.aspx http://msdn.microsoft.com/en-us/library/bb361254.aspx

hashset.RemoveWhere(s => s == "somestring");

You specify a condition/predicate as the parameter to the method. Any item in the hashset that matches the predicate will be removed.

This avoids the problem of modifying the hashset whilst it is being iterated over.


In response to your comment:

s  represents the current item being evaluated from within the hashset.

The above code is equivalent to:

hashset.RemoveWhere(delegate(string s) {return s == "somestring";});

or:

hashset.RemoveWhere(ShouldRemove);

public bool ShouldRemove(string s)
{
    return s == "somestring";
}

  EDIT:    

Something has just occurred to me: since HashSet is a set that contains no duplicate values, just calling hashset.Remove("somestring") will suffice. There is no need to do it in a loop as there will never be more than a single match.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1482234/hashset-iterating-while-removing-items-in-c-sharp

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils