C#中关于Dictionary的用法详解


当前第2页 返回上一页

创建及初始化


1

Dictionary<int,string> myDictionary=new Dictionary<int,string>();

添加元素


1

2

3

4

5

6

7

myDictionary.Add(1,"C#");

 

myDictionary.Add(2,"C++");

 

myDictionary.Add(3,"ASP.NET");

 

myDictionary.Add(4,"MVC");

通过Key查找元素


1

2

3

4

5

6

7

if(myDictionary.ContainsKey(1))

 

{

 

  Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

 

 }

通过KeyValuePair遍历元素


1

2

3

4

5

6

7

foreach(KeyValuePair<int,string> kvp in myDictionary)

 

{

 

    Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);

 

}

仅遍历键 Keys 属性


1

2

3

4

5

6

7

Dictionary<int,string>.KeyCollection keyCol = myDictionary.Keys;foreach(intkeyinkeyCol)

 

{

 

  Console.WriteLine("Key = {0}", key);

 

}

仅遍历值 Valus属性


1

2

3

4

5

6

7

Dictionary<int,string>.ValueCollection valueCol = myDictionary.Values;foreach(stringvalueinvalueCol)

 

{

 

   Console.WriteLine("Value = {0}", value);

 

}

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


1

2

3

4

5

6

7

8

9

10

11

myDictionary.Remove(1);if(myDictionary.ContainsKey(1))

 

{

 

  Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);

 

}else{

 

    Console.WriteLine("不存在 Key : 1");

 

 }

4.其它常见属性和方法的说明:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

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的用法详解的详细内容!

返回前面的内容

相关阅读 >>

.net中的序列化详解

c#中关于扩展方法的实例分析

.net中关于接口和类之间的区别介绍

c#中实现复制与删除文件的方法

关于.net(c#)正确读取中文编码文件的实例教程

c#基础之操作优化实例教程

linux下搭建.net core环境方法步骤

在linux下搭建.net core开发环境教程

.net mvc 使用ueditor上传图片

比较c#和java中面向对象语法的区别

更多相关阅读请进入《Dictionary》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...