eri*_*hak 4 .net c# dictionary list
我有以下代码:
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();
Run Code Online (Sandbox Code Playgroud)
现在我试图遍历所有月份,如下所示:
foreach (Dictionary<string, string> allMonths in allMonthsList)
Run Code Online (Sandbox Code Playgroud)
如何访问键值?难道我做错了什么?
Ser*_*kiy 11
foreach (Dictionary<string, string> allMonths in allMonthsList)
{
foreach(KeyValuePair<string, string> kvp in allMonths)
{
string year = kvp.Key;
string month = kvp.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
BTW年通常有一个多月.看起来你需要在这里查找,或者Dictionary<string, List<string>>存储一年中的所有月份.
解释通用字典Dictionary<TKey, TValue>实现IEnumerable接口,它返回一个遍历集合的枚举器.来自msdn:
出于枚举的目的,字典中的每个项目都被视为
KeyValuePair<TKey, TValue>表示值及其键的结构.返回项的顺序未定义.C#语言的foreach语句需要集合中每个元素的类型.由于
Dictionary<TKey, TValue>是键和值的集合,因此元素类型不是键的类型或值的类型.相反,元素类型是KeyValuePair<TKey, TValue>键类型和值类型.