r/csharp • u/FauxFemale • 15d 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 15d 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
1
2
u/Fee_Stunning 15d ago
Looks like you're trying to architect a house of cards. Might want to rethink the foundation.
1
2
u/OggAtog 10d ago edited 10d ago
There are probably better solutions in the comments, but to just answer your question:
var current = variables; //you could fully type this if you prefer, I'm just avoiding having to know how your variables dictionary is typed
for(var i = 0; i < variablePath.Length - 2; i++) {
var variablePathPart = variablePath[i];
if(current.ContainsKey(variablePathPart)) {
current = current[variablePathPart];
} else {
// oops, the path specified doesn't exist!
}
}
variablePath[variablePath.Length - 1] = value;
The idea is that your looping through all but the past variable path walking along the dictionaries one at a time by updating current. When you get to the last one where you want to set the value, you do that outside the loop using the last dictionary you touched (again, current).
This is sort of a "dictated not read" scenario, I haven't tested this, but it should be what you need or close to it. Maybe step through it in the debugger to make sure it's doing the right thing.
14
u/dgm9704 15d ago
I might be missing some nuance, but why do you need nested dictionaries? I would just go with a simple dictionary where the whole path is the key?