Traversing through an arbitrary dictionary tree structure in C#
- by Rudism
I am trying to write a recursive C# function that will operate on generic dictionaries of the form IDictionary<string, T> where T is either another IDictionary<string, T> or a string.
My first failed attempt looked something like this:
public string HandleDict(IDictionary<string, string> dict){
// handle the leaf-node here
}
public string HandleDict<T>(IDictionary<string, IDictionary<string, T>> dict){
// loop through children
foreach(string key in dict.Keys){
HandleDict(dict[key]);
}
}
I also tried variants of HandleDict<T>(IDictionary<string, T>) where T : IDictionary<string, T> but that also doesn't quite work. I know that what I want to do could be achieved through a custom class as the parameter instead of dictionaries, and that my attempts are conceptually flawed (there's no end to the recursion in the generic function). I would still like to know if there is actually a way to do what I want here using just generic IDictionaries.