Search code examples
c#dictionarycontainersgame-engine

C#: Easiest way to initialize & populate this particular 2D/3D Dictionary?


I have a bit of a complex dictionary.

It's a dictionary which holds two enumerated types & a List<>

Dictionary<BiomeType, Dictionary<LocationType, List<string>>> myDictionary;

So when I want to use it, I do something like this:

//Add "myString" to the List<string>
myDictionary[BiomeType.Jungle][LocationType.City1].Add("myString"));

When I try to add "myString" to myList, it throws an obvious & foreseeable error: "KeyNotFoundException: The given key was not present in the dictionary."

Is there any way in C# to automatically have the Dictionary add the Key if it isn't already there? I have a lot of BiomeTypes & even more LocationTypes. It would be a PITA to have to create each List, then create each locationtype dictionary, and then to add it for every BiomeType. All that work just to initialize this complex dictionary. Is there no easy way to do this?

I'm using this for gamedev, to store objects in a Dictionary, so I can access them by doing something like

BiomeType playerCurrentBiomeType;
LocationType playerCurrentLocationType;
LoadLevel(myDictionary[playerCurrentBiomeType][playerCurrentLocationType]);

//ex. myDictionary[BiomeType.Jungle][LocationType.CapitalCity]
//ex. myDictionary[BiomeType.Desert][LocationType.CapitalCity]
//ex. myDictionary[BiomeType.Desert][LocationType.City3]

Solution

  • Simply looping through every possible enum type & adding in a new value works to fully populate this multi-dimensional dictionary.

        Dictionary<BiomeType, Dictionary<LocationType, List<string>>> myDictionary = new Dictionary<BiomeType, Dictionary<LocationType, List<string>>>(); //No thanks to troll users like Peter.
        foreach (BiomeType biomeType in System.Enum.GetValues(typeof(BiomeType)))
        {
            Dictionary<LocationType, List<string>> newLocDict = new Dictionary<LocationType, List<string>>(); //No thanks to troll users like Peter.
    
            foreach (LocationType locType in System.Enum.GetValues(typeof(LocationType)))
            {
                List<string> newList = new List<string>(); 
                newLocDict.Add(locType, newList); //Add the final bit here & voila! Finished! No thanks to troll users like Peter.
            }
    
            myDictionary.Add(biomeType, newLocDict);
        }
    

    Robyn's solution works the same way if you don't want to fully populate the container with ALL enum values.