C# 之 Dictionary 详解
说明
- 必须包含名空间
System.Collection.Generic
- Dictionary里面的每一个元素都是一个键值对(由二个元素组成:键和值)
- 键必须是唯一的,而值不需要唯一的
- 键和值都可以是任何类型(比如:string, int, 自定义类型等等)
可以简单将 Dictionary 理解为键值对数据的集合
常规使用方法
// 定义 Dictionary<string, string> dictExecutes = new Dictionary<string, string>(); // 添加元素 dictExecutes.Add("bmp", "paint.exe"); dictExecutes.Add("dib", "paint.exe"); dictExecutes.Add("rtf", "wordpad.exe"); dictExecutes.Add("txt", "notepad.exe"); // 取值 Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]); // 改值 dictExecutes["rtf"] = "winword.exe"; Console.WriteLine("For key = 'rtf', value = {0}.", dictExecutes["rtf"]); // 遍历 KEY foreach( string key in dictExecutes.Keys ) Console.WriteLine("Key = {0}", key); // 遍历 VALUE foreach( string value in dictExecutes.Values ) Console.WriteLine("value = {0}", value); // 遍历字典 foreach( KeyValuePair<string, string> kvp in dictExecutes ) Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
// 添加存在的元素 try{ dictExecutes.Add("txt", "winword.exe"); }catch( ArgumentException ){ Console.WriteLine("An element with Key = 'txt' already exists."); } // 删除元素 dictExecutes.Remove("doc"); if( !dictExecutes.ContainsKey("doc") ) Console.WriteLine("Key 'doc' is not found."); // 判断键存在 if( openWith.ContainsKey("bmp") ) Console.WriteLine("An element with Key = 'bmp' exists.");
参数为其它类型
// 参数为其它类型 Dictionary<int, string[]> dictOthers = new Dictionary<int, string[]>(); dictOthers.Add(1, "1,11,111".Split(',')); dictOthers.Add(2, "2,22,222".Split(',')); Console.WriteLine(dictOthers[1][2]);
参数为自定义类型
// 首先定义类 class DouCube { private int _Code; public int Code { get{ return _Code; } set{ _Code = value; } } private string _Page; public string Page { get{ return _Page; } set{ _Page = value; } } } // 声明并添加元素 Dictionary<int, DouCube> MyTypes = new Dictionary<int, DouCube>(); for( int i = 1; i <= 9; i++ ){ DouCube elem = new DouCube(); elem.Code = i * 100; elem.Page = "http://www.doucube.com/" + i.ToString() + ".html"; MyTypes.Add(i, elem); } // 遍历元素 foreach( KeyValuePair<int, DouCube> kvp in MyTypes ){ Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page); }
分类:
.net / C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix