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

Recommended Answers

All 2 Replies

Could you just use a line like: runningcount[city]++;? Quick test:

Dictionary<object, int> runningcount = new Dictionary<object, int>();
object city = new object();
runningcount.Add(city, 3);
Console.WriteLine(runningcount[city]);
runningcount[city]++;
Console.WriteLine(runningcount[city]);
Console.ReadKey(true);

This program outputs:

3
4

The indexer property can also be set, which allows you to change the value. Unless there is something I am not understanding about your question?

Good Answer !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.