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

后端 未结 6 1889
粉色の甜心
粉色の甜心 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 17:55

    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!
        }
    }
    

提交回复
热议问题