views:

918

answers:

8

If I want to loop over a Dictionary(Key, Value)... why cant I add a new key-value pair in the loop?

Dictionary<string, string> persons = new Dictionary<string, string>();

persons.Add("roger", "12");
persons.Add("mary", "13");

foreach (KeyValuePair<string,string> person in persons)
{
 Console.WriteLine("Name: " + person.Key + ", Age: " + person.Value);
 persons.Add("Xico", "22");
}
A: 

That's just... odd. You're trying to add the same person again for each person already in the dictionary.

Also: why store the age as a string? int (or even DateTime) seems much more appropriate.

Joel Coehoorn
that was an example.
Narven
+8  A: 

You can't modify a dictionary when enumerating, simple as that. Otherwise when do you know you're done?

Otávio Décio
+7  A: 

If you want to do this you should get a copy of the Dictionary Object (can be done in many ways) then enumerate it, add what you want to the original.

Simply you can't add new items while enumerating an Dictionary.

dr. evil
A: 

Because it will change the items of the Dictionary that you are scrolling... It has no sense... (and you may looping forever)

tanathos
+20  A: 

It's because of the way the enumerator is constructed.

From MSDN Dictionary.Enumerator:

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

It's easy enough to get around this, though. Simply make a copy of the Dictionary (or it's keys) and iterate through it, adding/removing/etc. from the original Dictionary as needed.

tvanfosson
+1  A: 

When enumerating a collection (i.e. a foreach loop), it is not possible to add or remove items from the collection. Think of all the issues that would bring if that were allowed.

Antoine
A: 

You are attempting to alter the number of entries in the collection while iterating over the loop. A for loop can accomplish this, but the foreach iterater will not allow you do so.

A: 

Dictionary persons = new Dictionary(); persons.Add("roger", "12"); persons.Add("mary", "13"); for (int i = 0; i < persons.Count; i++){ Console.WriteLine("Name: " + persons[i].Key + ", Age: " + persons[i].Value); persons.Add("Xico", "22"); }

Be aware that this is an infinite loop, because you are always adding a person before you get to the last entry.