How To Modify An Element in the Dictionary Class?
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);
Re: How To Modify An Element in the Dictionary Class?
According to this, you should be able to just write:
++runningcount[city];
or
runningcount[city]++;
Did you try that?
The indexer of the Dictionary class provides both get and set capabilities, even creates a new entry if the specified one doesn't exist already.
Re: How To Modify An Element in the Dictionary Class?
Yeah. As Cthulhu said, that should work. You can also update or add using this pattern:
Code:
if( dict.TryGetValue(key, out val) )
dict[key] = newVal //Update on key exist
else
dict.Add(key, newVal) //Add on key not exist
Re: How To Modify An Element in the Dictionary Class?
You can also use ContainsKey:
Code:
if(dict.ContainsKey(key)){
dict[key]=value;
}else{
dict.Add(key,value);
}
That cat will get skinned one way or the other :-) Good luck!