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\"
Old question, but I may have just stumbled across an acceptable solution. I use a combination of TryGetValue, ternary operator and index assignment.
var thing = _dictionary.TryGetValue(key, out var existing) ? existing : _dictionary[key] = new Thing();
I have written a small example for that.
class Program
{
private static readonly Dictionary _translations
= new Dictionary() { { "en", "Hello world!" } };
private static string AddOrGetTranslation(string locale, string defaultText)
=> _translations.TryGetValue(locale, out var existingTranslation)
? existingTranslation
: _translations[locale] = defaultText;
static void Main()
{
var defaultText = "#hello world#";
Console.WriteLine(AddOrGetTranslation("en", defaultText)); // -> Hello world!
Console.WriteLine(AddOrGetTranslation("de", defaultText)); // -> #hello world#
Console.WriteLine(AddOrGetTranslation("de", "differentDefaultText")); // -> #hello world#
_translations["de"] = "Hallo Welt!";
Console.WriteLine(AddOrGetTranslation("de", defaultText)); // -> Hallo Welt!
}
}