|
-
August 18th, 2012, 06:19 PM
#1
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);
-
August 18th, 2012, 10:07 PM
#2
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.
Last edited by TheGreatCthulhu; August 18th, 2012 at 10:28 PM.
-
August 24th, 2012, 11:21 PM
#3
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
Best Regards,
BioPhysEngr
http://blog.biophysengr.net
--
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
-
August 25th, 2012, 01:41 PM
#4
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!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|