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

2019-12-26 12:14:14王振洲
易采站长站为您分析C#泛型集合Dictionary<K,V>的使用方法,本文讲解了Dictionary的多种操作方法,需要的朋友可以参考下    

1、要使用Dictionary集合,需要导入C#泛型命名空间

  System.Collections.Generic(程序集:mscorlib)

2、描述

   1)、从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成
   2)、任何键都必须是唯一的
   3)、键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值
   4)、Key和Value可以是任何类型(string,int,custom class 等)

3、创建及初始化

 

复制代码
   Dictionary<int, string> myDictionary = new Dictionary<int, string>();

 

4、添加元素

 

复制代码
   myDictionary.Add("C#",0);
   myDictionary.Add("C++",1);
   myDictionary.Add("C",2);
   myDictionary.Add("VB",2);

 

5、查找元素By Key

 

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

 

6.遍历元素 By KeyValuePair

 

复制代码
  foreach (KeyValuePair<string, int> kvp in myDictionary)
  {
    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
  }

 

7、仅遍历键 By Keys 属性

 

复制代码
  Dictionary<string, int>.KeyCollection keyCol = myDictionary.Keys;
  foreach (string key in keyCol/*string key in myDictionary.Keys*/)
  {
    Console.WriteLine("Key = {0}", key);
  }

 

8、仅遍历值By Valus属性