How To Modify An Element in the Dictionary Class?

Started by
2 comments, last by ApochPiQ 11 years, 8 months ago
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);
Advertisement
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

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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.
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.)

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement