C#中的Dictionary字典类常用方法介绍

 1 using System.Collections.Generic;//引用命名空间//Dictionary可以理解为散列集合
 2 public class DictionaryTest
 3 {
 4          public static void Main()
 5          {
 6                //1.初始化
 7                Dictionary<string, string> dicA = new Dictionary<string, string>();
 8                //2.添加元素 key,value->学号,姓名
 9                dicA.Add("A01", "张三");
10                dicA.Add("A02", "李四");
11                dicA.Add("B03", "王五");
12                dicA.Add("A03", "毛毛");
13                dicA.Add("B02", "张三");
14  
15                //3.通过key删除元素
16                dicA.Remove("A03");
17                //4.修改值
18                dicA("A02")="新值";
19                 
20                //5.假如不存在元素则加入元素
21                if (! dicA.ContainsKey("A08"))
22                    dicA.Add("A08", "哈哈");
23                 
24                //6.获取元素个数
25                int count= dicA.Count;
26  
27                //7.遍历集合
28                foreach (KeyValuePair<string, string> kvp in dicA)
29                {
30                       Console.WriteLine("学号:{0},姓名:{1}", kvp.Key, kvp.Value);
31                }
32  
33               //8.遍历键或值的集合
34               Dictionary<string, string>.KeyCollection allKeys = dicA.Keys;           
35               Console.WriteLine("最佳女主角:");
36               foreach (string oneKey in allKeys)
37               {
38                    Console.WriteLine(oneKey);
39               }
40  
41               //Dictionary<string, string>.ValueCollection allValues = dicA.Values;
42               //foreach (string oneValue in allValues)
43               //{
44               //     Console.WriteLine(oneValue);
45               //}
46  
47               //9.取值
48               string stuName=dicA("A01");
49  
50               //10.清空
51               dicA.Clear();
52                
53        }

 

转载于:https://www.cnblogs.com/zzp0320/p/7153693.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值