I encountered a situation like this where I had a hashtable in which the key is a string and the value is some object, and I had to change the values of all the keys [from zero to count] to null or some other value. I used the some of the facilities - enumerator, the Keys property etc provided by the hash table itself but it did not work out, and I spent too much time on this.
The interesting thing is that for the following code, the compiler spits an error saying "'System.Collections.IDictionaryEnumerator.Value' cannot be assigned to -- it is read only":-
But the solution was just bit out of sight while it was in hand. Just forget that you encountered this problem, and start again, you will have the solution simple like this:-
The interesting thing is that for the following code, the compiler spits an error saying "'System.Collections.IDictionaryEnumerator.Value' cannot be assigned to -- it is read only":-
IDictionaryEnumerator de = ht.GetEnumerator();while for this code
while (de.MoveNext())
{
de.Value = null;
}
foreach (string key in ht.Keys)it compiled successfully but threw a runtime exception [An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute].
{
ht[key] = null;
}
But the solution was just bit out of sight while it was in hand. Just forget that you encountered this problem, and start again, you will have the solution simple like this:-
ArrayList keys = new ArrayList(ht.Keys);And another thing I came to know was that the hash table entries are not maintained in the same order as they are inserted. I came to know that it is the inherent nature of the algorithm. That is basic but it was new to me.
foreach (string key in keys)
{
ht[key] = null;
}
Comments