目录
1.Dictionary的本质
可以将Dictionary理解为拥有泛型的Hashtable,它也是基于键的哈希代码组织起来的键/值对。键/值对类型从Hashtable的object变为了可以自己制定的泛型。
2.声明
需要引用命名空间:using System.Collections.Generic;
Dictionary<int,string> dictionary=new Dictionary<int,string>();
3.增删查改
增
值是可以一致的,但是键不可以。
//注意不能出现相同的键
dictionary.Add(1,"NicolePotter");
dictionary.Add(2,"NicolePotter");
dictionary.Add(3,"You are a wizard!");
删
//1.只能通过键去删除,删除不存在的键没有反应(不会出现报错)
dictionary.Remove(1);
dictionary.Remove(7);
//2.清空
dictionary.Clear();
查
//1.通过键查看值
//找不到就直接报错
Console.WriteLine(dictionary[1]);
//[ ]內的数字就是键查看
//2.查看是否存在
//根据键检测
if(dictionary.ContainsKey(1))
{
Console.WriteLine("存在键为1的键值对");
}
//根据值检测
if(dictionary.ContainsValue("123")
{
Console.WriteLine("存在值为123的键值对");
}
改
dictionary[1]="HarryPotter";
4.遍历
Console.WriteLine(dictionary.Count);
//1.遍历所有的键
foreach(int item in dictionary.Count);
{
Console.WriteLine(item);
Console.WriteLine(dictionary[item]);
}
//2.遍历所有的值
foreach(string item in dictionary.Values)
{
Console.WriteLine(item);
}
//3.键值对一起遍历
foreach(KeyValuePair<int,string> item in dictionary)
{
Console.WriteLine("键"+item.Key+"值"+item.Value);
}
//< , >里面的应该与Dictionary类型是一致的