前两天遇到一个<int, List<int>>结构的字典,查了资料才知道怎么顺序遍历,现在简单的整理一下,以免以后忘记。
public Dictionary<int, List<int>> dic = new Dictionary<int, List<int>>();
字典赋值的代码就不贴了,元素的数据结构大家都是知道的,只是value又是一个整型List而已,下面介绍两种简单的遍历的方法:
1. 直接遍历所有元素:
int i = 0;
Console.WriteLine("直接遍历元素:");
foreach(KeyValuePair<int, List<int>> pair in dic)
{
string str1 = null;
for(int index =0;index < pair.Value.Count;index ++)
{
str1 += pair.Value[index];
str1 += ", ";
}
Console.WriteLine("第" + i + "个元素: " + "key = " + pair.Key + ", values = " + str1);
i++;
}
运行结果如下,每个元素的所有值我连成一串打了出来:
2. 通过Key值作为索引来访问所有元素:
i = 0;
Console.WriteLine("\n把Key当做索引来访问元素");
List<int> keys = new List<int>(dic.Keys);
for (int index = 0; index < keys.Count; index ++ )
{
string str1 = null;
for (int index1 = 0; index1 < dic[keys[index]].Count; index1++)
{
str1 += dic[keys[index]][index1];
str1 += ", ";
}
Console.WriteLine("第" + i + "个元素: " + "key = " + keys[index] + ", values = " + str1);
i++;
}
运行结果同上,只是dic[keys[index]]这种List的List的写法不容易理解,不过个人觉得为提高程序的可读性,还是选择第一种方法更加直观一些哈。