Dictionary
一、本质
可以将 Dictionary 理解为 拥有泛型的 Hashtable 它也是基于键的哈希代码组织起来的 键/值对 键值对类型从 Hashtable 的 object 变为了可以自己制定的泛型
二、申明
1 2
| Dictionary<iht,string> dictionary = new Dictionary<int, string>();
|
三、增删查改
1.增
1 2 3 4
| dictionary.Add(1,"123"); dictionary.Add(2"222"); dictionary.Add(3,"222");
|
2.删
1 2 3 4 5 6
|
dictionary.Remove(1); dictionary.Remove(4);
dictionary.clear()
|
3.查
1 2 3 4 5 6 7 8 9 10 11
|
Console.WriteLine(dictionary[2]); Console.WriteLine(dictionary[1]);
if( dictionary.containsKey(4)) Console.writeLine("存在键为1的键值对")
if(dictionary.containsValue("1234")) Console.WriteLine("存在值为123的键值对");
|
4.改
1 2 3
| Console.WriteLine(dictionary[1]); dictionary[1]="555"; Console.WriteLine(dictionary[1]);
|
四、遍历
1 2 3 4 5 6 7 8 9 10 11 12
| foreach(int item in dictionary.Keys) { Console.WriteLine(item); Console.WriteLine(dictionary[item]); }
for(string item in dictionary.Values) Console.WriteLine(item);
foreach(KeyValuePair<int,string> item in dictionary) Console.WriteLine("键:"+item.Key +"值:"+ item.Value);
|