How do I access values from a Dictionary in an obj

2019-08-03 22:13发布

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 packlist;
using (var context = new JavascriptContext())
{
    context.Run(@"function packlist() { this.packs = new Array(); }
                var packlist = new packlist();
                packlist.packs[0] = { item1:""something"", item2:""something2"", item3:""something3"" };
                packlist.packs[1] = { item1:""something"", item2:""something2"", item3:""something3"" };
                packlist.packs[2] = { item1:""something"", item2:""something2"", item3:""something3"" };");
    packlist = context.GetParameter("packlist");
}

While debugging, the Locals window says the object looks like this this My question would be how would I go about accessing item1 from packlist.packs[0]?

3条回答
孤傲高冷的网名
2楼-- · 2019-08-03 22:48

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

http://msdn.microsoft.com/fr-fr/library/bb347013.aspx

查看更多
男人必须洒脱
3楼-- · 2019-08-03 22:48

I think it is:

var a = packlist.packs[0]["item1"];

查看更多
爷的心禁止访问
4楼-- · 2019-08-03 22:58

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"
查看更多
登录 后发表回答