Dictionary的遍历方法
来源:互联网 发布:elvis elvin 知乎 编辑:程序博客网 时间:2024/05/22 03:09
前两天遇到一个<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的写法不容易理解,不过个人觉得为提高程序的可读性,还是选择第一种方法更加直观一些哈。
0 0
- Dictionary的遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- c#遍历dictionary的几种方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- 遍历Dictionary和HashTable的方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- C# Dictionary 的几种遍历方法
- python遍历 truple list dictionary的几种方法
- Swift中 String、Array、Set、Dictionary的遍历方法
- .net 中Dictionary的遍历
- Hive 数据入库到HBase
- 《企业应用架构模式》 - 书摘精要
- 位运算
- AbsListView android:smoothScrollbar
- notifyDataSetChanged() 动态更新ListView
- Dictionary的遍历方法
- Vector用法
- Swift SpriteKit 忍者无敌
- hdu 4971
- 位运算符
- 字符串翻转(顺序翻转,每个子字符串顺序不变)
- java基础之Properties
- 创建JavaBean
- 关于break语句与switch语句