Find-or-insert with only one lookup in c# dictionary

后端 未结 6 1937
粉色の甜心
粉色の甜心 2021-01-17 17:38

I\'m a former C++/STL programmer trying to code a fast marching algorithm using c#/.NET technology...

I\'m searching for an equivalent of STL method \"map::insert\"

6条回答
  •  死守一世寂寞
    2021-01-17 18:04

    You can just assign your value in the following way:

    var dict = new Dictionary();
    dict[2] = 11;
    

    if value with key 2 does not exist - it will be added and otherwise it will be just overriden.

    Dictionary does not have method GetOrAdd, but ConcurrentDictionary from C# 4.0 does:

    var dict = new ConcurrentDictionary();
    dict[2] = 10;
    int a = dict.GetOrAdd(2, 11);// a == 10
    

提交回复
热议问题