第20节、C#Hashtable类:哈希表

C# Hashtable

在C#程序中,哈希表是表示”健-值Key/value”对的形式的集合。可理解:哈希表存放两个数组,一个数组用于存放Key值,一个数组用于存放Value值。

哈希表提供的构造方法很多,最常用的是不含参数的构造方法

Hashtable htb=new Hashtable()

  哈希表类中常用的属性和方法如下

属性或方法作用
Count 集合中存放的元素的实际个数
void Add(object key,object value) 向集合中添加元素
void Remove(object key) 根据指定的 key 值移除对应的集合元素
void Clear() 清空集合
ContainsKey (object key) 判断集合中是否包含指定 key 值的元素
ContainsValue(object value) 判断集合中是否包含指定 value 值的元素

示例:

 

 

 完整代码

 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace ConsoleApplication1
 9 {
10    public class Hashtable哈希表
11     {
12        public static void Main(string[] age)
13        {
14            //定义哈希表
15            Hashtable hs = new Hashtable();
16            //添加:
17            Console.WriteLine("添加");
18            hs.Add(1,"小爱");
19            hs.Add(2, "小美");
20            hs.Add(3, "小甜");
21            hs.Add(4, "小可");
22            hs.Add(5, "小醉");
23 
24            foreach (DictionaryEntry di in hs)
25            {
26                Console.WriteLine("学号编码{0},名字{1}",di.Key,di.Value);
27            }
28 
29            //清除所有
30            Console.WriteLine("清除所有");
31            hs.Clear();
32            foreach (DictionaryEntry di in hs)
33            {
34                Console.WriteLine("学号编码{0},名字{1}", di.Key, di.Value);
35            }
36 
37            Console.WriteLine("是否包含");
38            //是否包含
39            hs.Add(1, "小爱");
40            hs.Add(2, "小美");
41            hs.Add(3, "小甜");
42            hs.Add(4, "小可");
43            hs.Add(5, "小醉");
44            hs.Contains(5);
45            Console.WriteLine(hs.Contains(5) == true ? true : false);
46 
47            //浅表
48            Console.WriteLine("浅表");
49            hs.Clone();
50            foreach (DictionaryEntry di in hs)
51            {
52                Console.WriteLine("学号编码{0},名字{1}", di.Key, di.Value);
53            }
54 
55            //是否包含
56            Console.WriteLine("key是否包含");
57            hs.ContainsKey(4);
58            Console.WriteLine(hs.ContainsKey(4)==true?true:false);
59 
60            //Remove 移除指定元素
61            Console.WriteLine("移除指定元素");
62            hs.Remove(1);
63            foreach (DictionaryEntry di in hs)
64            {
65                Console.WriteLine("学号编码{0},名字{1}", di.Key, di.Value);
66            }
67 
68            Console.ReadLine();
69 
70 
71 
72        }
73     }
74 }
View Code

 

posted @ 2021-03-15 00:31  LiuzzBK  阅读(107)  评论(0编辑  收藏  举报