Dictionary, Enumeration and Remove

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
 
M

Marina

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top