- Home /
Enumerator, why don't you love me?
Ok,
I'm attempting to duplicate an XML document within Unity as a series of nested Hashtables. This works fine (so far) .. my problem is this:
In a Javascript Script, I can access the hashtable's properties as such:
myHashtable["atts"]["expand"] (works perfectly, however,)
I'm trying to access the same location within the hashtable, but through a C# script. I'm getting .. Index not allowed or something along those lines. I've read that to loop through a hashtable's properties, I should use Enumerator = GetEnumerator() .... I'm unfamiliar with C# (Flash AS background).
In short .. I want to loop through and see the properties/values from a hashtable in a C# Script and then use those values as titles for GUI buttons (think Expandable Tree Menu)
Can anybody help me out?! If I'm being unclear with my question, please let me know and I'll try to clarify.
Thanks!
Answer by duck · Oct 12, 2010 at 06:55 PM
To loop through every item in a Hashtable in C#:
foreach (DictionaryEntry entry in yourHashtable)
{
Debug.Log("Key: "+entry.Key+" Value: "+entry.Value);
}
As for recursively parsing a series of nested Hashtable, it is basically a case of making a function which accepts a hashtable as input, and inside that function, it loops through checking whether the current "entry.Value" is itself a Hashtable. If so, it calls "itself", passing the newly found Hashtable as the input:
void Start() { string result = Parse(nestedHashtables); }
string Parse( Hashtable data ) { foreach(DictionaryEntry entry in data) { if (entry.Value is Hashtable) { Parse(entry.Value); } else { // it's some kind of meaningful value!
} } }
You would then probably want to add some extra arguments to the recursive function so that data can be appended to a "flattened" version of the array, or keep track of the relative "depth" of the current recursion, etc.
Yeah, what he said. Alternatively, you can use the Hashtable method $$anonymous$$eys():
foreach (string key in myHashTable.$$anonymous$$eys) { string val = HashTable[key] as string; / do something with val here / } Note that the keys and the values of Hashtable aren't limited merely to strings.
It's also important to note that when you retrieve a $$anonymous$$ey or Value from a Hashtable, you typically have to re-cast it to the correct type, because it comes out as an "Object" type.
Oh, and another thing, if you have nested hashtables, you'll probably be wanting to look into recursive parsing! Fun! :-)
Boy did you hit the recursive parsing nail on the head! .. I'm actually working on that portion at the moment. $$anonymous$$y hashtable nesting goes pretty deep (depending on the imported X$$anonymous$$L structure). Any ideas?