Changing IDictionary value

  • Thread starter Thread starter tonci.tomic
  • Start date Start date
T

tonci.tomic

I have IDictionary with integers as keys and values.
Suppose I want to set value for key=42 to 1 if entry doesn't exist in
container. Otherwise, I want to increment value. I ended with:

IDictionary dict;
....
dict.Add(42, 0); // does nothing if entry exist
int val = (int)dict[42];
++val;
dict[42] = val;

But it looks realy ugly. 3X slower than it should be. Any suggestions?
 
tonci,

I would do the following:

// The value.
int pintValue = 0;

// Check to see if the key exists. If it does, then get that.
if (dict.Contains(42))
// Get the value.
pintValue = (int) dict[42];

// Increment the value and place in the dictionary.
dict[42] = ++pintValue;

Hope this helps.
 
I have IDictionary with integers as keys and values.
Suppose I want to set value for key=42 to 1 if entry doesn't exist in
container. Otherwise, I want to increment value. I ended with:

IDictionary dict;
...
dict.Add(42, 0); // does nothing if entry exist

Um, no - it throws an exception.
int val = (int)dict[42];
++val;
dict[42] = val;

But it looks realy ugly. 3X slower than it should be. Any suggestions?

Nope, that's exactly how you've got to do it. That's because you're
using a value type, which ends up being boxed. In order to change it,
you've got to unbox it, increment the value, then set the dictionary
value to the boxed version of the new value.

In IL it would be possible to increment within the box, but you can't
do that in C#.

An alternative way round it would be to have your own reference type
class as the value in the dictionary.
 
Back
Top