0

I want to be able to have a Dictionary< string, Dictionary< string, Dictionary< string,...>>>. I don't want to have Dictionary< string,object> as I have to cast the object back to whatever is boxed in there, making the traversal of the nested dictionaries difficult.

I would like to be able to do load the Dictionary from some serialized data source, like JSON, YAML, XML, and then be able to traverse with

dict["toplevel"]["nextlevel"]["and then some"]

BACKSTORY

I've been porting VBJSON to .Net. I have (had) Dictionary< Object,Object> into which I've embedded other Dictionary< Object,Object> and List< Object>. It annoys me that I can't readily traverse the resulting structure without lots of casts.

> thing["collection"]
Count = 4
    [0]: {[0, dog]}
    [1]: {[1, cat]}
    [2]: {[2, 2]}
    [3]: {[3, 3]}
> thing["collection"][0]
Cannot apply indexing with [] to an expression of type 'object'
> (thing["collection"])[0]
Cannot apply indexing with [] to an expression of type 'object'
> ((Dictionary<object,object>)thing["collection"])[0]
"dog"
bugmagnet
  • 7,631
  • 8
  • 69
  • 131
  • what's your question? What have you tried that isn't working? – Jonesopolis Apr 09 '14 at 02:12
  • you can define a base list/dict and then another to hold that (`Dictionary(Of String, Dictionary(Of T))`) then just nest it again if needed. BUT it is much cleaner to make at leas tone of them a class and internalize some of the complexity – Ňɏssa Pøngjǣrdenlarp Apr 09 '14 at 02:21
  • Duplicate of http://stackoverflow.com/questions/647533/recursive-generic-types ... or at least this expands on @jmoreno's answer below – bugmagnet Apr 09 '14 at 02:35

2 Answers2

3

You have to explicitly define the type (aka create your own class):

 Public Class RecursiveDict 
      Inherits Dictionary(of String, RecursiveDict)
 End Class

Or in c#

 class RecursiveDict : Dictionary<string, RecursiveDict> { }

Once the type has been declared it can be used.

jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • Ah, now this looks promising!! Mind you, so does http://msdn.microsoft.com/en-us/library/ms379574.aspx w.r.t. Graphs but that might be overkill – bugmagnet Apr 09 '14 at 02:24
1

Tree structure seems to be the best alternative for the kind of Nesting you are looking for.

You can easily serialize / deserialize the Tree structure to / from file.

public struct TreeNode
{
    public KeyValuePair<string, object> Data;
    public TreeNode Parent;
}
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110