Namespaces
System.Collections
name
Hashtable
describe
It is used to process and represent key-value pairs similar to keyvalue, where key can usually be used for quick lookup, and key is case-sensitive; value is used to store the value corresponding to key. The key-value key-value pairs in Hashtable are all of the object type, so Hashtable can support any type of key-value key-value pair.
Second, the simple operation of the hash table
Hashtable hshTable = new Hashtable(); // create a hash table
hshTable .Add("Person1", "zhanghf"); // add key-value pairs to the hash table
hshTable .Clear(); // remove the hash All key-value pairs in the table
hshTable .Contains("Person1"); //Determine whether the key is included in the hash table
string name = (string)hshTable["Person1"].ToString(); //Get the hash table The value of the specified key in
hshTable.Remove("Person1"); // Delete the key-value pair of the specified key in the hash table
IDictionaryEnumerator en = hshTable.GetEnumerator(); // Traverse all the keys in the hash table and read the corresponding value
while (en.MoveNext())
{
string str = en.Value.ToString();
}
The following console program will contain all of the above operations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
class
Program
{
static
void
Main(
string
[] args)
{
// 创建一个Hashtable实例
Hashtable ht=
new
Hashtable();
// 添加keyvalue键值对
ht.Add(
"A"
,
"1"
);
ht.Add(
"B"
,
"2"
);
ht.Add(
"C"
,
"3"
);
ht.Add(
"D"
,
"4"
);
// 遍历哈希表
foreach
(DictionaryEntry de
in
ht)
{
Console.WriteLine(
"Key -- {0}; Value --{1}."
, de.Key, de.Value);
}
// 哈希表排序
ArrayList akeys=
new
ArrayList(ht.Keys);
akeys.Sort();
foreach
(
string
skey
in
akeys)
{
Console.WriteLine(
"{0, -15} {1, -15}"
, skey, ht[skey]);
}
// 判断哈希表是否包含特定键,其返回值为true或false
if
(ht.Contains(
"A"
))
Console.WriteLine(ht[
"A"
]);
// 给对应的键赋值
ht[
"A"
] =
"你好"
;
// 移除一个keyvalue键值对
ht.Remove(
"C"
);
// 遍历哈希表
foreach
(DictionaryEntry de
in
ht)
{
Console.WriteLine(
"Key -- {0}; Value --{1}."
, de.Key, de.Value);
}
// 移除所有元素
ht.Clear();
// 此处将不会有任何输出
Console.WriteLine(ht[
"A"
]);
Console.ReadKey();
}
}
|