Dictionary泛型集合

让人想犯罪 __ 提交于 2020-01-27 02:28:28

文章目录

1 Dictionary<K, V>

1.1 Dictionary<K, V>简介

关于Dictionary<K, V>泛型集合:

  • Dictionary<K, V>通常称为字典,<K, V>约束集合中元素类型。
  • 编译时检查约束类型,无需装箱拆箱操作,与哈希表操作类似。

Dictionary<K, V>的存储结构:
在这里插入图片描述

1.2 Dictionary<K, V>的创建

  1. 使用Add添加:
//使用Add方法添加
Dictionary<string, Student> stuDic1 = new Dictionary<string, Student>();
stuDic1.Add("VIP1", student1);
stuDic1.Add("VIP2", student2);
stuDic1.Add("VIP3", student3);
stuDic1.Add("VIP4", student4);
stuDic1.Add("VIP5", student5);
  1. 使用集合初始化器:
//使用集合初始化器
Dictionary<string, Student> stuDic2 = new Dictionary<string, Student>()
{
    ["VIP1"]=student1,
    ["VIP2"] = student2,
    ["VIP3"] = student3,
    ["VIP4"] = student4,
    ["VIP5"] = student5,
};
  1. 集合的嵌套:
//集合的嵌套(比如:1班 5个学生成绩   2 班有5个学员成绩....)
List<int> class1List = new List<int> { 90, 80, 60, 79, 82 };
List<int> class2List = new List<int> { 93, 85, 60, 79, 82 };
List<int> class3List = new List<int> { 92, 80, 60, 89, 88 };

Dictionary<string, List<int>> classList = new Dictionary<string, List<int>>()
{
    ["软件1班"]= class1List,
    ["软件2班"] = class2List,
    ["软件3班"] = class3List
};

1.3 Dictionary<K, V>的访问和遍历

  1. 通过key访问value:
//通过key访问value
Student student = stuDic1["VIP3"];
Console.WriteLine(student.StudentName);
  1. 遍历key:
//遍历集合keys
foreach (string key in stuDic1.Keys)
 {
     Console.WriteLine(key);
 }
  1. 遍历values:
//遍历集合values
foreach (Student item in stuDic1.Values)
{
    Console.WriteLine(item.StudentId+"\t" + item.StudentName + "\t" + item.Age);
}

参考资料:

  1. .NET/C#工控上位机VIP系统学习班【喜科堂互联教育】
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!