首页 > 代码库 > C#中的Dictionary字典类常用方法介绍
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 }
C#中的Dictionary字典类常用方法介绍
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。