How Do I Access Values From A Dictionary In An Object?
Alright, I'm not sure if I'm asking the right question, but here goes. I'm using Javascript .NET to parse a Javascript object array. My code looks something like this: object packl
Solution 1:
Your packlist variable is a Dictionary with a single key, with the value being a object-array and every entry in that array also is a Dictionary. So getting the value would go something like this.
Dictionary<string,object> dicPacklist =(Dictionary<string,object>) packlist;
object[] packs = (object[])dicPacklist["packs"];
Dictionary<string,object> dicPackOne = (Dictionary<string,object>)packs[0];
object item1Value = dicPackOne["item1"]; //"something"
Solution 2:
The general structure is as follow:
PackList => Dictionary of <string, Dictionary<string,object>[]>
Meaning it is a dictionary where each value is an arry of dictionaries.
Should be
object[] arr = packlist["packs"] as object[];
Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
object item1 = dictPack["item1"];
Or
object packs;
if (packlist.TryGetValue("packs",out packs)) {
object[] arr = packs as object[];
Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
object item1 = dictPack["item1"];
}
The difference between them is that in the first, it is assumed that the key exists in the dictionary otherwise it throws an exception. In the second, it will try to get the value and tell you if the key is valid.
To check if a key is in the dictionary you can use this:
bool exists = packlist.ContainsKey("item1");
To run through all the items in the dictionary
foreach KeyPairValue<string,object> kp in packlist
{
string key = kp.Key;
object value = kp.Value;
}
Here's the MSDN link for the dictionary class
Solution 3:
I think it is:
var a = packlist.packs[0]["item1"];
Post a Comment for "How Do I Access Values From A Dictionary In An Object?"