using System;
using System.Collections.Generic;
namespace Dictionary泛型集合_02
{
/*
Dictionary<K,V> 字典集合
Dictionary<K, V> 泛型集合是Hashtable集合的泛型集合,即可以指定存储数据类型的集合。
Dictionary<K, V> 是Hashtable的泛型集合定义在System.Collections.Generic命名空间下,使用时需要先引入该命名空间,
该泛型集合相当于同时给容器的Key和Value贴上了指定类型的标签,一旦指定泛型类型,那么该容器就只能存储指定类型的键值对数据,方便开发者操作数据。
简要说明
1.Hashtable:非泛型哈希表,键值都是object,装箱拆箱、类型不安全
2.Dictionary<TKey,TValue>:泛型版哈希表,C# 专门用来替代 Hashtable
3.底层哈希寻址、扩容、冲突处理逻辑高度一致
4.日常开发优先用Dictionary,废弃Hashtable
核心区别
Hashtable:无泛型,值类型频繁装箱拆箱,性能差
Dictionary:泛型约束,类型安全,无装箱,效率更高
一句话总结
Dictionary 就是 Hashtable 的泛型优化版本。
*/
class Program
{
static void Main()
{
Dictionary<int, string> dic = new Dictionary<int, string>();
// 增
dic.Add(1, "北京");
dic.Add(2, "上海");
dic.Add(3, "广州");
// 查
Console.WriteLine(dic.Count); // 结果:3
Console.WriteLine(dic[1]); // 结果:"北京"
Console.WriteLine(dic.ContainsKey(1)); // 结果:True
Console.WriteLine(dic.ContainsValue("广州")); // 结果:True
// 改
dic[1] = "深圳";
Console.WriteLine(dic[1]);
// 删
dic.Remove(1); // 如果要删除的key不存在,运行会报销
Console.WriteLine(dic.Count);
// 遍历 键
foreach (int key in dic.Keys)
{
Console.WriteLine($"{key} - {dic[key]}");
}
// 遍历 值
foreach (string value in dic.Values)
{
Console.WriteLine($"{value}");
}
// 遍历:开发中常用这种方式
foreach (KeyValuePair<int, string> keyValue in dic)
{
Console.WriteLine($"{keyValue.Key} - {keyValue.Value}");
}
// 清除
dic.Clear();
Console.WriteLine(dic.Count);
Console.ReadKey();
}
//=======================【Dictionary集合的 初始化方法】=============================
//旧的初始化方法
private Dictionary<string, int> OldMethod()
{
Dictionary<string, int> student = new Dictionary<string, int>();
student.Add("张三", 25);
student.Add("李四", 34);
student.Add("王五", 26);
return student;
}
//新的初始化方法
private Dictionary<string, int> NewMethod()
{
Dictionary<string, int> student = new Dictionary<string, int>()
{
["张三"] = 25,
["李四"] = 34,
["王五"] = 26
};
return student;
}
}
}