Dictionary, Enumeration and Remove

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a type

Dictionary<int, List<int>> oKP = new Dictionary<int, List<int>>();

Im populating the dictionary so that a key is associated with a list of
integers. I then remove some, or possible all integers from the list by using
foreach:

foreach (int i in oKP.Keys)
{
foreach (int j in oKP)
{
if (oKP.ContainsKey(j))
{
if (oKP[j].Contains(i)) oKP[j].Remove(i);
}
}
}

I'd like to add a test which determines if the list is now empty
(oKP.Count == 0) and if so deletes the key and list from the dictionary -
like so:

foreach (int i in oKP.Keys)
{
foreach (int j in oKP)
{
if (oKP.ContainsKey(j))
{
if (oKP[j].Contains(i)) oKP[j].Remove(i);
if (0 == oKP[j].Count) oKP.Remove(j);
}
}
}

However when the remove of the dictionary entry is actioned I get an error:

Collection was modified; enumeration operation may not execute.

Now I understand why this happens, my question is how do I iterate over the
Dictionary and remove entries with a count of 0? What alternative can I use
to foreach that allows me to delete an entry?

Thanks in advance
 
This is because you are not supposed to alter the collection while going
through it using an enumerator (which is what for each is doing behind the
scenes).
Solution: use a for or while loop.
 
Back
Top