Hashtable problem
-
Hashtable approval = new Hashtable(); //then I added some keys to it and set the value to "" //I need to set its value to "" again by below foreach foreach( object obj in approval.Keys ) { approval[obj] = ""; } //But it said that "Collection was modified; enumeration operation may not execute." //Pls help me to make this possible. Thanks a lot for your attention.
-
Hashtable approval = new Hashtable(); //then I added some keys to it and set the value to "" //I need to set its value to "" again by below foreach foreach( object obj in approval.Keys ) { approval[obj] = ""; } //But it said that "Collection was modified; enumeration operation may not execute." //Pls help me to make this possible. Thanks a lot for your attention.
MSDN - foreach: The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. MSDN - Hashtable.Keys Property: The returned ICollection is not a static copy; instead, the ICollection refers back to the keys in the original Hashtable. Therefore, changes to the Hashtable continue to be reflected in the ICollection. An alternative approach could looke like this:
Hashtable ht = new Hashtable();
ht.Add("one", 1);
ht.Add("two", 2);
ht.Add("three", 3);
ht.Add("four", 4);ICollection keys = ht.Keys;
object[] copiedKeys = new object[keys.Count];
keys.CopyTo(copiedKeys, 0);
foreach(object key in copiedKeys)
{
ht[key] = "";
}Alexandre Kojevnikov MCAD charter member Leuven, Belgium
-
MSDN - foreach: The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects. MSDN - Hashtable.Keys Property: The returned ICollection is not a static copy; instead, the ICollection refers back to the keys in the original Hashtable. Therefore, changes to the Hashtable continue to be reflected in the ICollection. An alternative approach could looke like this:
Hashtable ht = new Hashtable();
ht.Add("one", 1);
ht.Add("two", 2);
ht.Add("three", 3);
ht.Add("four", 4);ICollection keys = ht.Keys;
object[] copiedKeys = new object[keys.Count];
keys.CopyTo(copiedKeys, 0);
foreach(object key in copiedKeys)
{
ht[key] = "";
}Alexandre Kojevnikov MCAD charter member Leuven, Belgium