Hannes Pavelka
It isn't rocket science. Well, unless of course you're NASA

How to modify a hashtable in a foreach loop

Thursday, November 17, 2005 8:16 PM

If you try to modify a collection while enumarte over it you will get an Exception : "Collection was modified; enumeration operation may not execute."

Personally, I simply copy the keys:

Hashtable t = new Hashtable();
t.Add(1, 1);
t.Add(2, 2);
ArrayList a = new ArrayList(t.Keys);
foreach (int i in a)
{
  t.Remove(i);
}

Eric Gunnerson has another aproach. You can read it here.


Feedback

# re: How to modify a hashtable in a foreach loop

Your method seems far simpler, therefore better! 11/18/2005 1:43 PM | Brian

# re: How to modify a hashtable in a foreach loop

Thaks, it works perfect. 4/7/2006 6:41 AM | Franky

# re: How to modify a hashtable in a foreach loop

Simple and effective... nice! 2/23/2007 5:32 PM | Josue Aranda

# re: How to modify a hashtable in a foreach loop

Very Helpful. good approach
4/12/2007 3:23 PM | ram

# re: How to modify a hashtable in a foreach loop

works great. thx! 4/26/2007 5:22 AM | Chris

# re: How to modify a hashtable in a foreach loop

an alternative approach for this is to use DictionaryEntry

foreach (DictionaryEntry Item in t)
{
item["myKey"] = "some value";
} 6/4/2007 9:26 PM | uzair

Post a comment