1.要运用Dictionary鸠合,须要导入C#泛型定名空间
System.Collections.Generic //顺序集:mscorlib
2.Dictionary的形貌
从一组键(Key)到一组值(Value)的映照,每个增加项都是由一个值及其相干系的键构成
任何键都必须是唯一的
键不能为空援用null(VB中的Nothing),若值为援用范例,则可认为空值
Key和Value可所以任何范例(string,int,custom class 等)
3.Dictionary经常使用用法:以 key 的范例为 int , value的范例为string 为例
建立及初始化
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: //猎取与指定的键相干联的值。
以上就是C#中关于Dictionary的用法详解的细致内容,更多请关注ki4网别的相干文章!