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); }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号