How do I access values from a Dictionary in an object?

99封情书 提交于 2020-01-05 08:07:16

问题


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

My question would be how would I go about accessing item1 from packlist.packs[0]?

回答1:


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




回答2:


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"



回答3:


I think it is:

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



来源:https://stackoverflow.com/questions/10790840/how-do-i-access-values-from-a-dictionary-in-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!