gpt4 book ai didi

c# - 如何获取数组中字典的键和值?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:31 26 4
gpt4 key购买 nike

我在key中添加了一些valuearray字典,现在当我尝试获取所有对时,出现了一些错误:

这是代码:

protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue.ToString() == "January")
{
Dictionary<string, int>[] temperatures = new Dictionary<string, int>[2];
temperatures[0]=new Dictionary<string, int>();
temperatures[1]=new Dictionary<string, int>();
temperatures[0].Add("Day1",22);
temperatures[1].Add("Day2",23);

foreach (KeyValuePair<string,int> temperture in temperatures[])
{
Label1.Text = string.Format("at {0} the temperture is {1} degree", temperture.Key, temperture.Value);
}
}
}


现在错误或问题是此行:

foreach (KeyValuePair<string,int> temperture in temperatures[])


如果我写 temperatures[]我得到错误消息:


  语法错误,期望值
  索引器有1个参数,但它使用0个参数调用


如果我添加 temperatures[0]temperatures[1]之类的索引,我只会得到第一项或第二项的键和值,但不是全部。

我该怎么办?

最佳答案

由于temperatures是字典数组-您必须明确指出要访问的数组元素。

因此,如果您需要遍历数组中所有字典的所有对-只需再添加一个循环即可:

foreach (var t in temperatures)
{
foreach (KeyValuePair<string,int> temperture in t)
{
// do whatever yoou need
}
}

关于c# - 如何获取数组中字典的键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com