Nadav Stern Nadav Stern - 5 months ago 27
C# Question

changing a value of a term while iterating a HashSet

i am using a HashSet in order to avoid having two (or more)items with the same value inside my collection , on my work i need to iterate over my hashset and remove its values but unfortunatly i cant do so , what i am trying to do is:

string newValue = "";
HashSet<string> myHashSet;
myHashSet = GetAllValues(); // lets say there is a function which fill the hashset
foreach (string s in myHashSet)
newValue = func(s) // lets say that func on some cases returns s as it was and
if(s != newValue) // for some cases returns another va


thanks in advance for your kind help

Jon Jon

You cannot modify the container while it's being iterated. The solution would be to project the initial set into a "modified" set using LINQ (Enumerable.Select), and create a new HashSet from the results of the projection.

Since if there is a func with the appropriate signature you can directly stick it into the Enumerable.Select method, and since HashSet has a constructor that accepts an IEnumerable<T>, it all comes down to one line:

var modifiedHashSet = new HashSet(myHashSet.Select(func));