Sign in to follow this  

How To Modify An Element in the Dictionary Class?

This topic is 1978 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
You can use the [] syntax to set the value once it has been Added to the dictionary:

[code]Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("testing", 41);
++myDictionary["testing"];

MessageBox.Show(myDictionary["testing"].ToString()); // Displays 42[/code]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
You are correct. Just be warned that trying to use [] to [i]read[/i] 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.)

Share this post


Link to post
Share on other sites
Sign in to follow this