文章目录
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>的创建
- 使用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);
- 使用集合初始化器:
//使用集合初始化器
Dictionary<string, Student> stuDic2 = new Dictionary<string, Student>()
{
["VIP1"]=student1,
["VIP2"] = student2,
["VIP3"] = student3,
["VIP4"] = student4,
["VIP5"] = student5,
};
- 集合的嵌套:
//集合的嵌套(比如: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>的访问和遍历
- 通过key访问value:
//通过key访问value
Student student = stuDic1["VIP3"];
Console.WriteLine(student.StudentName);
- 遍历key:
//遍历集合keys
foreach (string key in stuDic1.Keys)
{
Console.WriteLine(key);
}
- 遍历values:
//遍历集合values
foreach (Student item in stuDic1.Values)
{
Console.WriteLine(item.StudentId+"\t" + item.StudentName + "\t" + item.Age);
}
参考资料:
来源:CSDN
作者:SlowIsFastLemon
链接:https://blog.csdn.net/SlowIsFastLemon/article/details/103581390