How To Modify An Element in the Dictionary Class?
=======================================
C# has this cool Dictionary class that you can use like a Hash Table. Is there a way of changing the value of an indexed element without resorting to removing it like this?
int value = runningcount[city];
runningcount.Remove(city);
runningcount.Add(city, ++value);
How To Modify An Element in the Dictionary Class?
Started by athono, Aug 18 2012 04:46 PM
3 replies to this topic
Ad:
#2 Moderators - Reputation: 7515
Posted 18 August 2012 - 05:35 PM
You can use the [] syntax to set the value once it has been Added to the dictionary:
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("testing", 41);
++myDictionary["testing"];
MessageBox.Show(myDictionary["testing"].ToString()); // Displays 42
Maker of Machinery
[Work - ArenaNet] [Epoch Language] [Scribblings] [Journal - peek into my shattered mind]
[Work - ArenaNet] [Epoch Language] [Scribblings] [Journal - peek into my shattered mind]
#3 Members - Reputation: 305
Posted 18 August 2012 - 05:46 PM
You can also use the [] syntax to set new values. This should come with a warning sign, though; there's no protection against over-writing existing values.
Edited by Narf the Mouse, 18 August 2012 - 05:46 PM.
Now open: MouseProduced Games
#4 Moderators - Reputation: 7515
Posted 18 August 2012 - 07:17 PM
You are correct. Just be warned that trying to use [] to read a value that doesn't exist will throw an exception. (That's why you can't, for example, use ++ on a value that hasn't been added yet - it must read the value first, then increment it, then set it.)
Maker of Machinery
[Work - ArenaNet] [Epoch Language] [Scribblings] [Journal - peek into my shattered mind]
[Work - ArenaNet] [Epoch Language] [Scribblings] [Journal - peek into my shattered mind]






