سؤال

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"
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top