0

In other words, is this safe?

Hashtable myDict = ... //fill with some data

foreach (DictionaryEntry pair in myDict)
{
   if (someCondition)
       myDict.Remove(pair.Key);
}

It doesnt seem to have any side effects in my application so far.

edit: i have to mention that in my specific case, this dictionary contains only 1 entry.

edit2: sorry, the datatype is a Hashtable not a Dictionary.

clamp
  • 33,000
  • 75
  • 203
  • 299
  • Check here: http://stackoverflow.com/questions/11365725/delete-item-from-dictionary-while-iterating-over-it – Hassan Apr 17 '14 at 12:33
  • have you tried running a test sample like that? It will throw an error. Also a `DictionaryEntry` is the wrong type – Jonesopolis Apr 17 '14 at 12:40
  • I am sorry, I gave the wrong datatype. it is not a dictionary but a Hashtable – clamp Apr 17 '14 at 12:56

3 Answers3

7

No it is not safe, the contract of IEnumerator specifies that MoveNext should throw an exception if the underlying collection was modified after the enumerator was created.

Lee
  • 142,018
  • 20
  • 234
  • 287
1

No, it is not safe. with every removed entry it will reduce index no and will move to next element with increasing current index no, so it will create problem there.

0

@Lee gave you the answer.

It would be safe this way:

var toDelete = myDict.Where(someCondition).ToArray();
foreach (DictionaryEntry pair in toDelete)
    myDict.Remove(pair.Key);
vtortola
  • 34,709
  • 29
  • 161
  • 263