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
{
myHashSet.Remove(s);
myHashSet.Add(newValue);
}
}
thanks in advance for your kind help
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 newHashSetfrom the results of the projection.Since if there is a
funcwith the appropriate signature you can directly stick it into theEnumerable.Selectmethod, and sinceHashSethas a constructor that accepts anIEnumerable<T>, it all comes down to one line: