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

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.

Posted on Thursday, November 17, 2005 8:16 PM Misc | Back to top


Comments on this post: How to modify a hashtable in a foreach loop

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
Your method seems far simpler, therefore better!
Left by Brian on Nov 18, 2005 1:43 PM

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
Thaks, it works perfect.
Left by Franky on Apr 07, 2006 6:41 AM

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
Simple and effective... nice!
Left by Josue Aranda on Feb 23, 2007 5:32 PM

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
Very Helpful. good approach
Left by ram on Apr 12, 2007 3:23 PM

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
works great. thx!
Left by Chris on Apr 26, 2007 5:22 AM

# re: How to modify a hashtable in a foreach loop
Requesting Gravatar...
an alternative approach for this is to use DictionaryEntry

foreach (DictionaryEntry Item in t)
{
item["myKey"] = "some value";
}
Left by uzair on Jun 04, 2007 9:26 PM

Your comment:
 (will show your gravatar)


Copyright © Hannes Pavelka | Powered by: GeeksWithBlogs.net