C# Dictionary 简单介绍

本文详细介绍了C#中Dictionary类的使用方法,包括属性、方法及其应用场景。通过实例演示了如何添加、获取、更新及遍历字典中的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类:Dictionary

属性

属性用途
Comparer获取用于确定字典中的键是否相等的 IEqualityComparer。
Count获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目。
Item获取或设置与指定的键相关联的值。
Keys获取包含 Dictionary<TKey, TValue> 中的键的集合。
Values获取包含 Dictionary<TKey, TValue> 中的值的集合。

方法

方法说明
Add将指定的键和值添加到字典中。
Clear从 Dictionary<TKey, TValue> 中移除所有的键和值。
ContainsKey确定 Dictionary<TKey, TValue> 是否包含指定的键。
ContainsValue确定 Dictionary<TKey, TValue> 是否包含特定值。
Equals(Object)确定指定的 Object 是否等于当前的 Object。 (继承自 Object。)
Finalize允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。
1    //定义
 2     Dictionary<string, string> openWith = new Dictionary<string, string>();
 3  
 4 
 5     //添加元素
 6     openWith.Add("txt", "notepad.exe");
 7     openWith.Add("bmp", "paint.exe");
 8     openWith.Add("dib", "paint.exe");
 9     openWith.Add("rtf", "wordpad.exe");
10  
11 
12     //取值
13     Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
14  
15 
16     //更改值
17     openWith["rtf"] = "winword.exe";
18     Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
19  
20 
21     //遍历key
22     foreach (string key in openWith.Keys)
23     {
24         Console.WriteLine("Key = {0}", key);
25     }
26  
27 
28 29     //遍历value
30     foreach (string value in openWith.Values)
31     {
32         Console.WriteLine("value = {0}", value);
33     }
34 
35     //遍历value, Second Method
36     Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
37     foreach (string s in valueColl)
38     {
39         Console.WriteLine("Second Method, Value = {0}", s);
40     }
41 42  
43 
44     //遍历字典
45     foreach (KeyValuePair<string, string> kvp in openWith)
46     {
47         Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
48     }
49  
50 
51 52     //添加存在的元素
53     try
54     {
55         openWith.Add("txt", "winword.exe");
56     }
57     catch (ArgumentException)
58     {
59         Console.WriteLine("An element with Key = \"txt\" already exists.");
60     }
61 62  
63 
64 65     //删除元素
66     openWith.Remove("doc");
67     if (!openWith.ContainsKey("doc"))
68     {
69         Console.WriteLine("Key \"doc\" is not found.");
70     }
71  
73 
74     //判断键存在
75     if (openWith.ContainsKey("bmp")) // True 
76     {
77         Console.WriteLine("An element with Key = \"bmp\" exists.");
78     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值