gpt4 book ai didi

c# - 如何遍历字典列表?

转载 作者:太空狗 更新时间:2023-10-30 00:03:15 28 4
gpt4 key购买 nike

我有以下代码:

List<Dictionary<string, string>> allMonthsList = new List<Dictionary<string, string>>();
while (getAllMonthsReader.Read()) {
Dictionary<string, string> month = new Dictionary<string, string>();
month.Add(getAllMonthsReader["year"].ToString(),
getAllMonthsReader["month"].ToString());
allMonthsList.Add(month);
}
getAllMonthsReader.Close();

现在我正在尝试遍历所有月份,如下所示:

foreach (Dictionary<string, string> allMonths in allMonthsList)

如何访问键值?我做错了什么吗?

最佳答案

foreach (Dictionary<string, string> allMonths in allMonthsList)
{
foreach(KeyValuePair<string, string> kvp in allMonths)
{
string year = kvp.Key;
string month = kvp.Value;
}
}

BTW 一年通常有一个多月。看起来你需要在这里查找,或者 Dictionary<string, List<string>>用于存储一年中的所有月份。

解释 通用词典 Dictionary<TKey, TValue> 工具 IEnumerable接口(interface),它返回一个遍历集合的枚举器。来自 msdn:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

The foreach statement of the C# language requires the type of each element in the collection. Since the Dictionary<TKey, TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair<TKey, TValue> of the key type and the value type.

关于c# - 如何遍历字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718713/

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