首页 > 其他 > 详细

字典遍历

时间:2017-05-06 11:28:47      阅读:332      评论:0      收藏:0      [点我收藏+]
 1 using System;
 2 using System.Collections.Generic;
 3 public class Example
 4 {
 5          public static void Main()
 6          {
 7                //一、创建泛型哈希表,然后加入元素
 8                Dictionary<string, string> oscar = new Dictionary<string, string>();
 9                oscar.Add("哈莉?贝瑞", "《死囚之舞》");
10                oscar.Add("朱迪?丹奇", "《携手人生》");
11                oscar.Add("尼科尔?基德曼", "《红磨坊》");
12                oscar.Add("詹妮弗?康纳利", "《美丽心灵》");
13                oscar.Add("蕾妮?齐维格", "《BJ单身日记》");
14 
15                //二、删除元素
16                oscar.Remove("詹妮弗?康纳利");
17 
18                //三、假如不存在元素则加入元素
19                if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不伦之恋》");
20                
21 
22                //四、显然容量和元素个数
23                Console.WriteLine("元素个数: {0}", oscar.Count);
24 
25                //五、遍历集合
26                Console.WriteLine("74届奥斯卡最佳女主角及其电影:");
27                foreach (KeyValuePair<string, string> kvp in oscar)
28                {
29                       Console.WriteLine("姓名:{0},电影:{1}", kvp.Key, kvp.Value);
30                }
31 
32               //六、得到哈希表中键的集合
33               Dictionary<string, string>.KeyCollection keyColl = oscar.Keys;
34               //遍历键的集合
35               Console.WriteLine("最佳女主角:");
36               foreach (string s in keyColl)
37               {
38                    Console.WriteLine(s);
39               }
40 
41               //七、得到哈希表值的集合
42               Dictionary<string, string>.ValueCollection valueColl = oscar.Values;
43               //遍历值的集合
44               Console.WriteLine("最佳女主角电影:");
45               foreach (string s in valueColl)
46               {
47                    Console.WriteLine(s);
48               }
49 
50               //八、使用TryGetValue方法获取指定键对应的值
51               string slove = string.Empty;
52               if (oscar.TryGetValue("朱迪?丹奇", out slove))
53                      Console.WriteLine("我最喜欢朱迪?丹奇的电影{0}", slove);
54               else
55                      Console.WriteLine("没找到朱迪?丹奇的电影");
56 
57               //九、清空哈希表
58               oscar.Clear();
59               Console.ReadLine();
60        }
61 }

 

字典遍历

原文:http://www.cnblogs.com/AaronBlogs/p/6815888.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!