Traversing through an arbitrary dictionary tree structure in C#
Posted
by Rudism
on Stack Overflow
See other posts from Stack Overflow
or by Rudism
Published on 2010-05-26T21:35:33Z
Indexed on
2010/05/26
21:41 UTC
Read the original article
Hit count: 276
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.
© Stack Overflow or respective owner