【学习笔记】C# 字典
- 字典
- Dictionary是存储键和值的集合
- Dictionary是无序的,键Key是唯一的
- 使用时,首先要引入泛型集合命名空间 using System.Collections.Generic;
- 创建一个字典对象
- Dictionary<key, value> dic = new Dictionary<key, value>();
- Dictionary<string, int> dic = new Dictionary<string, int>();
- Add方法,用来添加键值对
- dic.Add("小明", 13);
- dic.Add("小红", 15);
- 通过 Remove() 方法,中设定Key 值 ,来移除value所在的键值对
- dic.Remove("小红");
- Clear()清空当前字典里的所有内容
- dic.Clear();
- Count获取当前字典里value的个数
- int count = dic.Count;
- Console.WriteLine("当前字典中有 " + count + " 个键值对!");
- ContainsKey()方法查看当前字典里是否含有Key-"小明"
- bool b = dic.ContainsKey("小明");
- if(b)
- {
- Console.WriteLine("存在小明的年龄!");
- }else
- {
- Console.WriteLine("不存在小明的年龄!");
- }
- ContainsValue()方法直接查看是否存在当前的Value
- bool b2 = dic.ContainsValue(10);
- if (b2)
- {
- Console.WriteLine("存在年龄为10的人!");
- }
- else
- {
- Console.WriteLine("不存在年龄为10的人!");
- }
- TryGetValue()方法,尝试获取指定的Key所对应的Value
- int s;
- bool bb = dic.TryGetValue("xiaoming", out s);
- //如果当前字典包含“小明”这个key,那么就获取对应的value并保存在s中 ,bb=true
- //如果当前字典不包含“小明”这个key,那么s=null, bb = false;
- 通过 Key 获取 value
- int age = dic["小明"];
- Console.WriteLine("小明的年龄是: " + age);
-
1 using System; 2 //引入泛型集合命名空间 3 using System.Collections.Generic; 4 5 namespace DictionaryDemo 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 //创建一个字典对象,key 的类型是 string , value 的类型是int 12 Dictionary<string, int> dic = new Dictionary<string, int>(); 13 //Add方法,用来添加键值对 14 dic.Add("小明", 13); 15 dic.Add("小红", 15); 16 17 18 //通过 Remove() 方法,中设定Key 值 ,来移除value所在的键值对 19 dic.Remove("小红"); 20 21 //Clear()清空当前字典里的所有内容 22 dic.Clear(); 23 24 25 //Count获取当前字典里value的个数 26 int count = dic.Count; 27 Console.WriteLine("当前字典中有 " + count + " 个键值对!"); 28 29 //ContainsKey()方法查看当前字典里是否含有Key-"小明" 30 bool b = dic.ContainsKey("小明"); 31 if (b) 32 { 33 Console.WriteLine("存在小明的年龄!"); 34 } 35 else 36 { 37 Console.WriteLine("不存在小明的年龄!"); 38 } 39 40 //ContainsValue()方法直接查看是否存在当前的Value 41 bool b2 = dic.ContainsValue(10); 42 if (b2) 43 { 44 Console.WriteLine("存在年龄为10的人!"); 45 } 46 else 47 { 48 Console.WriteLine("不存在年龄为10的人!"); 49 } 50 51 //TryGetValue()方法,尝试获取指定的Key所对应的Value 52 int s; 53 bool bb = dic.TryGetValue("xiaoming", out s); 54 //如果当前字典包含“小明”这个key,那么就获取对应的value并保存在s中 ,bb=true 55 //如果当前字典不包含“小明”这个key,那么s=null, bb = false; 56 if (bb) 57 { 58 Console.WriteLine("包含“小明”这个key"); 59 } 60 else 61 { 62 Console.WriteLine("不包含“小明”这个key!"); 63 } 64 65 //通过 Key 获取 value 66 int age = dic["小明"]; 67 Console.WriteLine("小明的年龄是: " + age); 68 } 69 } 70 }
这是一只小菜鸟的成长历程,在学习Unity3d及C#的道路上,希望能越走越远!