Enumerating Hashtables
A lengthy thread was started about enumerating a hashtable and modifying the values. The individual was getting the standard modification within a foreach exception thrown. I had suggested the following code and I seem to have the shortest and easiest method in doing so...
ArrayList arrayList = new ArrayList(hashtable.Keys); IEnumerator listEnumerator = arrayList.GetEnumerator(); while (listEnumerator.MoveNext()) { hashtable[listEnumerator.Current] = "value"; } // while
Is there a better or recommended way to do this? The above seemed right to me.
UPDATE: Jerry Pisk had suggested that I was doing extra code when you can just enumerate using foreach and modify the values. That was the whole point of me writing the first paragraph above Jerry. Doing that causes an exception. You can enumerate all day long and “read” values, but you can not modify the values within the foreach loop. Which brings you to the code I wrote above...