Search code examples
c#dictionarykey-valuepopulate

Best way to add key-value pairs to a dictionary in C#


I am using a dictionary in C# to store some key-value pairs and had a question on the best way to populate the dictionary.

I need to do some other operations in order to find and add my key-value pairs to my dictionary. After those operations I may have found a key-value to add to the dictionary or I could have found nothing.

My question is how I should populate the dictionary?

  • Should I use a function that returns a key-value pair if found and otherwise an empty one contained within a dictionary.Add(function()) call? I don't want to add an empty key-value pair to the dictionary, so I'm not sure how the return call for that function would work, or

  • Should I pass the dictionary to the function and add to it if needed? Like:

    function(dictionary) 
    {
        if (pair found)
        {
            dictionary.add(pair)
        }
    }
    

Solution

  • Not sure what you ask here, but here is how I handle dictionary to either add or update a value based on a key:

    string key = "some key here";
    string value = "your value";
    if (myDict.ContainsKey(key))
    {
        myDict[key] = value;
    }
    else
    {
        myDict.Add(key, value);
    }
    

    You can wrap this in a method if you like:

    void AddOrUpdate(Dictionary<string, string> dict, string key, string value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] = value;
        }
        else
        {
            dict.Add(key, value);
        }
    }
    
    //usage:
    AddOrUpdate(myDict, "some key here", "your value");
    

    You can also use the TryGetValue method but can't see any obvious advantage in this.