如何遍历嵌套的Dictionary

本文关键字:Dictionary string object 嵌套 何遍历 遍历 | 更新日期: 2023-09-27 18:03:31

我有一个JSON文件,我需要使用类System.Web.Script.Serialization进行反序列化。以下代码:

string json = File.ReadAllText(@"C:'file.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
var dict = ser.Deserialize<Dictionary<string, object>>(json);

创建一个嵌套字典,如下所示:

Dictionary<string, Object> outerDictionary;
Dictionary<string, Object> middleDictionary;
Dictionary<string, string> innerDictionary;

我现在需要从innerDictionary中抓取一些值到c#对象类中,如:

public class Location
{
   public string Id { get; set; }
   public string Name { get; set; }
   public string Street { get; set; }
   public string City { get; set; }
   public string State { get; set; }
   public string Zip { get; set; }
}

所以我的问题是,我如何迭代嵌套字典以获得我需要的最内层的值?

Jonesopolis的帮助下,我现在有了正确的循环结构,但我仍然无法从最内层的字典中获得值?

foreach (var outer in dict)
{
    foreach (var middle in (Dictionary<string, object>)outer.Value)
    {
        foreach (var inner in (ArrayList)middle.Value)
        {
            foreach (var loc in (Dictionary<string, object>)inner)
            {
            }
         }
    }
}

如何遍历嵌套的Dictionary<string, object>

如果你不喜欢Jonesopolis的答案中嵌套的foreach,那么你可以这样使用LINQ:

var data = from outer in dict
           from middle in (Dictionary<string, object>) outer.Value
           from inner in (Dictionary<string, string>) middle.Value
           select new { outer, middle, inner };
foreach (var item in data) {
    // do things with item.inner
}

如果你真的想处理这些对象:

foreach(var outer in dict)
{
    foreach (var middle in (Dictionary<string, object>) outer.Value)
    {
         foreach (var inner in (Dictionary<string, string>) middle.Value)
         {
              var location = new Location();
              location.Id = inner["Id"]; 
              //etc..
         }      
    }
}
虽然

,但创建一个可以反序列化json的类结构会更好,它可以准确地表示您的数据,而不是强制转换字典。