目录
Dictionary的本质
可以将Dictionary理解为 拥有泛型的Hashtable
它也是基于键的哈希代码组织起来的 键/值对
键值对类型从Hashtable的object变为了可以自己制定的泛型
申明
需要引用命名空间 using System.Collections.Generic
Dictionary<int, string> dictionary = new Dictionary<int, string>();
增删查改
增
注意:不能出现相同键
dictionary.Add(1, "123");
dictionary.Add(2, "222");
dictionary.Add(3, "222");
//dictionary.Add(3, "123");
删
1.只能通过键去删除
删除不存在键 没反应
dictionary.Remove(1);
dictionary.Remove(4);
2.清空
dictionary.Clear();
查
1.通过键查看值 找不到直接报错
Console.WriteLine(dictionary[2]);
Console.WriteLine(dictionary[1]);
2.查看是否存在
根据键检测
if( dictionary.ContainsKey(4) )
{
Console.WriteLine("存在键为1的键值对");
}
根据值检测
if (dictionary.ContainsValue("1234"))
{
Console.WriteLine("存在值为123的键值对");
}
改
Console.WriteLine(dictionary[1]);
dictionary[1] = "555";
Console.WriteLine(dictionary[1]);
遍历
用foreach遍历
Console.WriteLine(dictionary.Count);
1.遍历所有键
foreach (int item in dictionary.Keys)
{
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);
}
练习
cs
main
{
Dictionary<char , int> dir = new Dictionary<char, int>();
Console.WriteLine("请输入字母");
string a= Console.ReadLine();
for (int i = 0; i < a.Length; i++)
{
if (dir.ContainsKey(a[i])) //这里的a[i]直接获取String里面的char字符
{ //因为String本质就是Char[] 类型
dir[a[i]]++;
}
else
dir.Add (a[i], 1);
}
foreach (char c in dir.Keys)
{
Console.WriteLine(c+" " + dir[c] +"次");
}
}
cs
class Program
{
public static void Main()
{
string[] h = new string[] {"一","二","三","四","五","六","七","八","九","十"};
Dictionary<int,String> dic = new Dictionary<int,String>();
for (int i = 1 ,j=0; i < 10; i++)
{
dic.Add(i, h[j]);
j++;
}
Console.WriteLine("输入三个数");
string temp= Console.ReadLine();
int [] b = new int[temp.Length];
for (int i = 0; i < temp .Length; i++)
{
b[i]=temp[i]-'0';
}
for (int i = 0; i < b.Length; i++)
{
Console.WriteLine(dic[b[i]]);
}
}
}