c# - Adding an item to a dictionary efficiently but doing += instead of = -


i have dictionary maps strings doubles.

i have line:

leaves[child.value] += branchprobability; 

it crashes because instead of doing: add default value of 0 if not found, return 0, add branchprobability, set new value = 0 + branchprobability, starts doing on key throws keynotfoundexception.

the thing can think of is:

if(!leaves.containskey(child.value))    leaves[child.value] = branchprobability; else    leaves[child.value] += branchprobability; 

but requires lookup contains.

would there more efficient way while avoiding contains check?

the following code defines (and tests, if paste linqpad) class let using +=. however, if passing dictionary around lots of places, won't work, because has hide indexer new rather overriding (the dictionary's indexer isn't virtual).

one way around creating defaultingdictionary implementer of idictionary<tkey, tvalue> , within class having private member that's dictionary, , delegating calls methods on idictionary through - except indexer, yourself. still can't pass things expecting dictionary, change things accept idictionary instead.

void main() {     var dict = new defaultingdictionary<string, double>();      dict["one"] = 1;      dict["one"] += 1;     dict["two"] += 1;      console.writeline(dict["one"]);     console.writeline(dict["two"]); }  class defaultingdictionary<tkey, tvalue> : dictionary<tkey, tvalue> {     public new tvalue this[tkey key]     {                 {             tvalue v;             if(trygetvalue(key, out v))             {                 return v;             }             return default(tvalue);         }          set         {             base[key] = value;         }     } } 

honestly, lot of work able += thing. should check. there's no performance benefit this, makes code more complicated. if check, reading understand what's going on.


Comments