Search code examples
c#asp.net-mvcdictionarykeyvaluepair

Dictionary if Key exist append if not add new element C#


I am having

Dictionary<String, List<String>> filters = new Dictionary<String, List<String>>();

which is having values like country = us. till now I am able to add it when key is not repeated. now when key country is repeated. it is showing that the key is already present.

what I want is How to add multiple values in the same key. I am not able to do it. Please suggest something.

for (int i = 0; i < msgProperty.Value.Count; i++)
{
    FilterValue.Add(msgProperty.Value[i].filterValue.Value);
    filterColumn = msgProperty.Value[i].filterColumnName.Value;
    filters.Add(filterColumn, FilterValue);
}

what I want

country = US,UK


Solution

  • The different types of all your variables are a bit confusing, which won't help you writing the code. I'm assuming you have a Dictionary<string, List<string>> where the key is a "language" and the value is a list of countries for that language, or whatever. Reducing a problem to a minimal set that reproduces the issue is very helpful when asking for help.

    Anyway assuming the above, it's as simple as this:

    • Try to get the dictionary["somelanguage"] key into existingValue.
    • If it doesn't exist, add it and store it in the same variable.
    • Add the List<string> to the dictionary under the "somelanguage" key.

    The code will look like this:

    private Dictionary<string, List<string>> dictionary;
    
    void AddCountries(string languageKey, List<string> coutriesToAdd)
    {
        List<string> existingValue = null;
    
        if (!dictionary.TryGetValue(languageKey, out existingValue))
        {
            // Create if not exists in dictionary
            existingValue = dictionary[languageKey] = new List<string>()
        }
    
        existingValue.AddRange(coutriesToAdd);
    }