Remove Item from hashtable

  • Thread starter Thread starter MFRASER
  • Start date Start date
M

MFRASER

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 );

}
 
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.
 
Agreed.

I think your first line of code should read "hashtable.Count" not
"hashtable.Count - 1"

And perhaps one could still use the more concise foreach. e.g.:

object keys[] = new object[hashtable.Keys.Count];
hashtable.Keys.CopyTo(keys, 0);

foreach(object key in keys)
{
hashtable.Remove(key);
}

Felix

Nicholas Paldino said:
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]
- (e-mail address removed)

MFRASER said:
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 );

}
 
Back
Top