Jump to content

View more

Image of the Day

Boxes as reward for our ranking mode. ヾ(☆▽☆)
#indiedev #gamedev #gameart #screenshotsaturday https://t.co/ALF1InmM7K
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.


Sign up now

How To Modify An Element in the Dictionary Class?

4: Adsense

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
3 replies to this topic

#1 athono   Members   

132
Like
0Likes
Like

Posted 18 August 2012 - 04:46 PM

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

#2 ApochPiQ   Moderators   

22538
Like
2Likes
Like

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

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

#3 Narf the Mouse   Members   

322
Like
3Likes
Like

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.


#4 ApochPiQ   Moderators   

22538
Like
1Likes
Like

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.)
Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]




Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.