Hashtable
- 是一种集合,存储的元素是键值对(Key - Value - Pair)
引用声明
using System.Collections;
Hashtable table = new Hashtable();
增
table.Add("name", "Lee");
table.Add(1, "Hello World ~");
table.Add("age", 10);
table.Add("data", null);
//table.Add("data", null); // Error 因为存在了data
查 - 注意顺序
foreach (DictionaryEntry dictionary in table)
{
Console.WriteLine($"{dictionary.Key} => {dictionary.Value}");
// data =>
// age => 10
// 1 => Hello World ~
// name => Lee
}
// 获取key的集合
ICollection keys = table.Keys;
foreach (object key in keys)
{
Console.WriteLine($"{key} => {table[key]}");
// data =>
// age => 10
// 1 => Hello World ~
// name => Lee
}
改
table["name"] = 123;
删
table.Remove("name");
foreach (DictionaryEntry dictionary in table) {
Console.WriteLine($"{dictionary.Key} => {dictionary.Value}");
// data =>
// age => 10
// 1 => Hello World ~
}
其他方法
- 判断是否包含
key
为age
的元素
bool res = table.Contains("age");
Console.WriteLine(res); // True