C#入门Dictionary<k,v>泛型集合
关于Dictionary<k,v>泛型集合
- Dictionary<k,v>通常成为字典,<k,v>约束集合中元素类型;
- 编译时检查类型约束,无需装箱拆箱操作,与哈希表操作类似;
1 static void Main(string[] args) 2 { 3 //创建几个学员对象 4 Student objStudent1 = new Student(1001, "小明"); 5 Student objStudent2 = new Student(1002, "小王"); 6 Student objStudent3 = new Student(1003, "小林"); 7 Student objStudent4 = new Student(1004, "小周"); 8 Student objStudent5 = new Student(1005, "小郭"); 9 10 //创建集合对象 11 List<Student> objStuList = new List<Student>(); 12 objStuList.Add(objStudent1); 13 objStuList.Add(objStudent2); 14 objStuList.Add(objStudent3); 15 objStuList.Add(objStudent4); 16 //创建Dictionary泛型集合 17 Dictionary<string,Student > objDicStuList= new Dictionary<string, Student>(); 18 objDicStuList.Add("林", objStudent3); 19 objDicStuList.Add("王", objStudent2); 20 objDicStuList.Add("周", objStudent4); 21 objDicStuList.Add("郭", objStudent5); 22 23 //通过键值来直接显示值,查询 24 Console.WriteLine(objDicStuList["王"].StudentName); 25 26 //遍历key值 27 foreach (var item in objDicStuList.Keys) 28 { 29 Console.WriteLine(item); 30 } 31 Console.WriteLine("---------"); 32 //遍历 value 33 foreach (var item in objDicStuList.Values) 34 { 35 Console.WriteLine(item.StudentId+"\t"+item.StudentName); 36 } 37 Console.ReadLine(); 38 }