Dictionary with list of strings as value

前端 未结 4 1825
旧时难觅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:04

    A simpler way of doing it is:

    var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());
    
    0 讨论(0)
  • 2020-12-23 21:07

    I'd wrap the dictionary in another class:

    public class MyListDictionary
    {
    
        private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();
    
        public void Add(string key, string value)
        {
            if (this.internalDictionary.ContainsKey(key))
            {
                List<string> list = this.internalDictionary[key];
                if (list.Contains(value) == false)
                {
                    list.Add(value);
                }
            }
            else
            {
                List<string> list = new List<string>();
                list.Add(value);
                this.internalDictionary.Add(key, list);
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-23 21:15

    To do this manually, you'd need something like:

    List<string> existing;
    if (!myDic.TryGetValue(key, out existing)) {
        existing = new List<string>();
        myDic[key] = existing;
    }
    // At this point we know that "existing" refers to the relevant list in the 
    // dictionary, one way or another.
    existing.Add(extraValue);
    

    However, in many cases LINQ can make this trivial using ToLookup. For example, consider a List<Person> which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:

    var namesBySurname = people.ToLookup(person => person.Surname,
                                         person => person.FirstName);
    
    0 讨论(0)
  • 2020-12-23 21:23

    Just create a new array in your dictionary

    Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
    myDic.Add(newKey, new List<string>(existingList));
    
    0 讨论(0)
提交回复
热议问题