MFRASER,
If you want to remove items from a Hashtable in a loop, you must use the
"for" statement, not the "foreach" statement. The reason for this is that
trying to modify the collection while enumerating through it will throw an
exception.
That being said, you can get the keys, and enumerate through those, and
remove the items, like this:
// Get the keys collection, and copy to an array.
object keys[] = new object[hashtable.Count - 1];
// Copy.
hashtable.Keys.CopyTo(keys, 0);
// A key in the collection.
object key;
// Cycle through the collection backwards.
for (int index = keys.Length - 1; index >= 0; --index)
{
// Remove the item.
hashtable.Remove(keys[index]);
}
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"MFRASER" <mf*****@henwoodenergy.com> wrote in message
news:ef**************@TK2MSFTNGP12.phx.gbl...
How do I go about looping through a hash table and removing items. I know
how do this in a collectionbase, but can't iterate through the hash table
with out getting an error.
Here is my sample code for a collection base
for(int i = this.Values.Count; i > 0 ; i--)
{
//Set local object
MyObject aObject = this.ItemByIndex(i)
if (aObject .Type== aType)
this.Remove(aObject );
}