Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hashtable Errors.

Status
Not open for further replies.

Chopsaki

Programmer
Nov 21, 2001
85
US
Ok there is probably a very straight forward answer to this but I fail to understand how the enumeration of a hashtable works in C#. I have a hashtable (myHash) that I am trying to enumerate and loop through. The key is a string and the value is an int. All I am trying to do it decrease every value by 1. Everytime I run the code below it throws back an error (Collection was modified; enumeration operation may not execute).
How do I get around this?
int tmpInt;
Hashtable myHash = new Hashtable();
populate(myHash);
lock(myHash.SyncRoot)
{
IDictionaryEnumerator hashEn = myHash.GetEnumerator();
while(hashEn.MoveNext())
{
tmpInt = (int)hashEn.Value;
tmpInt--;
myHash[hashEn.key] = tmpInt;


}
}
 
Think of the enumerator as the iterator through the hash table. Since the hash table implements IDictionaryEnumerator, once you've set the Enumerator object (hashEn by your example) by the GetEnumerator method, your whole hash table is now "inside" the enumerator object.

Therefore, as you move next in the enumerator, you are actually moving to the next object within your hash table (OK, not necessarily since the hash table doesn't necessarily persist data in the order you enter it). From that, hashEn.Value would be the value you stored at that
index in the hash table.

Copy this code into the Form1_Load event of a new project. It might offer a visual explanation for you.

private void Form1_Load(object sender, System.EventArgs e)
{
Hashtable myHashTable = new Hashtable();
IDictionaryEnumerator enMyHashTable;

myHashTable.Add("First", "FirstValue");
myHashTable.Add("Second", "SecondValue");
myHashTable.Add("Third", "ThirdValue");
myHashTable.Add("Fourth", "FourthValue");
myHashTable.Add("Fifth", "FifthValue");

enMyHashTable = myHashTable.GetEnumerator();

while(enMyHashTable.MoveNext())
{
MessageBox.Show(enMyHashTable.Value.ToString());
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top