Jump to content

  • Log In with Google      Sign In   
  • Create Account


How To Modify An Element in the Dictionary Class?


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

Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 14430

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


#3 Narf the Mouse   Members   -  Reputation: 318

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   -  Reputation: 14430

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




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.



PARTNERS