在C#字典中循环使用JSON


Looping through JSON in a C# dictionary

我正在尝试实现我已经在C#中创建的PHP函数,但我不知道C#中用于导航字典的语法!(PHP中的关联数组)。我所做的基本上是制作一个foreach循环来打印关联数组中属性的每个实例。我不确定我的问题是否完全清楚,为了更容易,C#的等价物是什么?

foreach ( $data->response->docs as $info )
{
    echo "{$info->EventId},";
    echo "{$info->VenueName},";
}

我只需要在语法方面朝着正确的方向推动一下。

感谢

编辑-

哦,当我发布这个问题时,我累了。我的问题是如何导航从JSON序列化的字典。在我的例子中,我从这个样本数据中解析了两个属性:-

{"responseHeader":{"status":0,"QTime":2},"response":{"facet_counts":{},"numFound":110,"docs":[{"VenueSEOLink":"/Aberdeen-Music-Hall-tickets-Aberdeen/venue/443660","VenueId":"10512085..... 

等等…

因此,我试图弄清楚如何通过dict.(C#等价于->)

在C#中,可以使用System.Collections.Dictionary或通用System.Collections.Generic.Dictionary<TKey, TObject>。我推荐通用字典,因为它是强类型的,并且不必每次检索对象时都强制转换内容。

假设您的EventId是int,您可以这样访问它:

Dictionary<int, string> info = new Dictionary<int, string>();
int eventId = 42;
info[eventId] = "Some value";
var value = info[eventId];
// value = "Some value" as string

如果您使用的是string密钥,只需将字典定义和密钥类型从int更改为string即可。

要对字典(或任何实现IEnumerable的集合或其他对象)进行迭代,您可以使用与PHP中基本相同的语法:

foreach (var item in info) {
  // Do something with item
}

更多信息Systems.Collections.Generic.IDictionary在这里。