C#如何使用Dictionary

来源:互联网 发布:java中sort的用法 编辑:程序博客网 时间:2024/05/18 21:10

 

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


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

2、描述


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

 

3、常用用法:以 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);}


通过Remove方法移除指定的键值

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


 

参考资料:  C#中Dictionary的用法      http://www.studyofnet.com/news/45.html

 

原创粉丝点击