C#泛型集合Dictionary 的使用方法

2019-12-26 12:14:14王振洲

 

复制代码
  Dictionary<string, int>.ValueCollection valueCol = myDictionary.Values;
  foreach (int value in valueCol)
  {
    Console.WriteLine("Value = {0}", value);
  }

 

9.移除指定的键值By Remove方法

 

复制代码
  myDictionary.Remove("C#");
  if (myDictionary.ContainsKey("C#"))
  {
    Console.WriteLine("Key:{0},Value:{1}", "C#", myDictionary["C#"]);
  }
  else
  {
    Console.WriteLine("不存在 Key : C#");
      }

 

在System.Collections.Generic命名空间中,与ArrayList相对应的泛型集合是List<T>,与 HashTable相对应的泛型集合是Dictionary<K,V>,其存储数据的方式与哈希表相似,通过键/值来保存元素,并具有泛型的全部特征,编译时检查类型约束,读取时无须类型转换。

电话本存储的例子中,使用Dictionary<K,V>来存储电话本信息,代码如下:

 

复制代码
Dictionary<string,TelNote> ht=new Dictionary<string,TelNote>();

 

在Dictionary<K,V>声明中,“<string,TelNote>”中的string表示集合中Key的类型,TelNote表示Value的类型,定义Dictionary<K,V>泛型集合中的方法如下:

 

复制代码
Dictionary<K,V> students=new Dictionary<K,V>();

 

其中“K”为占位符,具体定义时用存储键“Key”的数据类型代替,“V”也是占位符,用元素的值“Value”的数据类型代替,这样就在定义该集合时,声明了存储元素的键和值的数据类型,保证了类型的安全性。

Dictionary<K,V>中元素的操作方法与HashTable相似,添加元素,获取元素,删除元素,遍历集合元素的方法基本相同。

Dictionary<K,V>和HashTable的区别
Dictionary<K,V>和HashTable的相同点:添加元素,删除元素,通过键访问值的方法相同。