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'); }
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.