1.要使用Dictionary集合,需要導入C#泛型命名空間
System.Collections.Generic //程序集:mscorlib
從一組鍵(Key)到一組值(Value)的映射,每一個添加項都是由一個值及其相關連的鍵組成
任何鍵都必須是唯一的
鍵不能為空引用null(VB中的Nothing),若值為引用類型,則可以為空值
Key和Value可以是任何類型(string,int,custom class 等)
創建及初始化
Dictionary<int,string> myDictionary=new Dictionary<int,string>();
添加元素
myDictionary.Add(1,"C#"); myDictionary.Add(2,"C++"); myDictionary.Add(3,"ASP.NET"); myDictionary.Add(4,"MVC");
通過Key查找元素
if(myDictionary.ContainsKey(1)) { Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]); }
通過KeyValuePair遍歷元素
foreach(KeyValuePair<int,string> kvp in myDictionary) { Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value); }
僅遍歷鍵 Keys 屬性
Dictionary<int,string>.KeyCollection keyCol = myDictionary.Keys; foreach(intkeyinkeyCol) { Console.WriteLine("Key = {0}", key); }
僅遍歷值 Valus屬性
Dictionary<int,string>.ValueCollection valueCol = myDictionary.Values; foreach(stringvalueinvalueCol) { Console.WriteLine("Value = {0}", value); }
通過Remove方法移除指定的鍵值
myDictionary.Remove(1); if(myDictionary.ContainsKey(1)) { Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]); } else { Console.WriteLine("不存在 Key : 1"); }
4.其它常見屬性和方法的說明:
Comparer: // 獲取用於確定字典中的鍵是否相等的 IEqualityComparer。 Count: // 獲取包含在 Dictionary中的鍵/值對的數目。 Item: //獲取或設置與指定的鍵相關聯的值。 Keys: // 獲取包含 Dictionary中的鍵的集合。 Values: // 獲取包含 Dictionary中的值的集合。 Add: // 將指定的鍵和值添加到字典中。 Clear: //從 Dictionary中移除所有的鍵和值。 ContainsKey: //確定 Dictionary是否包含指定的鍵。 ContainsValue: //確定 Dictionary是否包含特定值。 GetEnumerator: // 返回循環訪問 Dictionary的枚舉數。 GetType: // 獲取當前實例的 Type。 (從 Object 繼承。) Remove: //從 Dictionary中移除所指定的鍵的值。 ToString: //返回表示當前 Object的 String。 (從 Object 繼承。) TryGetValue: //獲取與指定的鍵相關聯的值。