using System; using System.Collections.Generic; public class Example { public static void Main() { //一、创建泛型哈希表,然后加入元素 Dictionary<string, string> oscar = new Dictionary<string, string>(); oscar.Add("哈莉?贝瑞", "《死囚之舞》"); oscar.Add("朱迪?丹奇", "《携手人生》"); oscar.Add("尼科尔?基德曼", "《红磨坊》"); oscar.Add("詹妮弗?康纳利", "《美丽心灵》"); oscar.Add("蕾妮?齐维格", "《BJ单身日记》"); //二、删除元素 oscar.Remove("詹妮弗?康纳利"); //三、假如不存在元素则加入元素 if (!oscar.ContainsKey("茜茜?斯派克")) oscar.Add("茜茜?斯派克", "《不伦之恋》"); //四、显然容量和元素个数 Console.WriteLine("元素个数: {0}", oscar.Count); //五、遍历集合 Console.WriteLine("74届奥斯卡最佳女主角及其电影:"); foreach (KeyValuePair<string, string> kvp in oscar) { Console.WriteLine("姓名:{0},电影:{1}", kvp.Key, kvp.Value); } //六、得到哈希表中键的集合 Dictionary<string, string>.KeyCollection keyColl = oscar.Keys; //遍历键的集合 Console.WriteLine("最佳女主角:"); foreach (string s in keyColl) { Console.WriteLine(s); } //七、得到哈希表值的集合 Dictionary<string, string>.ValueCollection valueColl = oscar.Values; //遍历值的集合 Console.WriteLine("最佳女主角电影:"); foreach (string s in valueColl) { Console.WriteLine(s); } //八、使用TryGetValue方法获取指定键对应的值 string slove = string.Empty; if (oscar.TryGetValue("朱迪?丹奇", out slove)) Console.WriteLine("我最喜欢朱迪?丹奇的电影{0}", slove); else Console.WriteLine("没找到朱迪?丹奇的电影"); //九、清空哈希表 oscar.Clear(); Console.ReadLine(); } }
C# 字典 Dictionary 遍历
原创
©著作权归作者所有:来自51CTO博客作者编程的世界你不懂的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
python优雅遍历字典删除元素
Python基础知识
删除元素 Python 简洁性 -
c# 遍历字典改key
void test(int cur, int cnt) { List<string> list = new List<string>(m_pptDa
string 遍历 c# 字典 修改key -
C# Dictionary 字典
说明 必须包含名空间System.Collection.Generic Dictionary里面
键值对 反序列化 自定义类型 微信 取值 -
【C#】字典集合Dictionary
【代码】【C#】字典集合Dictionary。
c# 开发语言 System Linq 代码示例 -
C#字典底层原理
Dictionary是一种键值对的形式存放数据,即 key和value一一映射。key的类型没有限制,可以是整数、字符串甚至是实例对象
哈希算法 算法 数组 链表 List -
C# 字典 Dictionary 遍历
转自原文 C# 字典 Dictionary 遍历
C# 语法 泛型 c# 删除元素 c -
c 遍历python字典 python for遍历字典
python中遍历字典的操作一个python字典可能只包含几个键值对,也可能包含数量庞大的键值对。鉴于字典可能包含大量的数据,python支持对字典遍历。一、遍历所有的键值对使用for循环来遍历字典。但是遍历字典时,键值对的返回顺序也与存储顺序不同。在python不关心键值对的存储顺序,它只跟踪键和值的关联关系。实例:(使用items()方法,将键与值分别赋值给变量key和value.)
c 遍历python字典 python 字典应用程序实例 python中elements遍历 python在字典中插入新的数据 python字典中append