Dictionary with list of strings as value

前端 未结 4 1833
旧时难觅i
旧时难觅i 2020-12-23 20:55

I have a dictionary where my value is a List. When I add keys, if the key exists I want to add another string to the value (List)? If the key doesn\'t exist then I create a

4条回答
  •  误落风尘
    2020-12-23 21:07

    I'd wrap the dictionary in another class:

    public class MyListDictionary
    {
    
        private Dictionary> internalDictionary = new Dictionary>();
    
        public void Add(string key, string value)
        {
            if (this.internalDictionary.ContainsKey(key))
            {
                List list = this.internalDictionary[key];
                if (list.Contains(value) == false)
                {
                    list.Add(value);
                }
            }
            else
            {
                List list = new List();
                list.Add(value);
                this.internalDictionary.Add(key, list);
            }
        }
    
    }
    

提交回复
热议问题