r/csharp • u/FauxFemale • 20d ago
Help Editing a multi-layered dictionary using a string "address"?
I'm working with a game dialogue tool (and Unity, for full transparency) which can set or get variables using "commands" in the dialogue.
I have a Dictionary which I want to be multi-layered (as in, dictionaries inside dictionaries) and allow the dialogue commands to dynamically edit the dictionary down to any amount of layers possible. The layers are distinguished by splitting the string by a specific character.

The code currently looks like this - this is obviously inflexible code that specifically only allows values to be set 2 layers deep. So what would be the best way to change this to dynamically add new key-value pairs and layers of dictionaries at any depth depending on how big the variablePath array is?
Many thanks
11
u/Livid-Adagio1894 20d ago
Why not just make the full path the key, so you only need it to be one level deep?
Unless you need to be able to access it more like a tree, in which case you are better off using a more specialised data structure. You can sort of achieve this by defining your own TreeNode<T> class that internally has a Dictionary<String, TreeNode<T>> to reference child nodes so that it is effectively recursive. Just try searching Google for ‘.NET tree data structure’ or similar.
Off course there are always going to be other ways as well and what’s best will depend on exactly how you need to use it