- 哈希表是一种数据类型,跟集合差不多。
- 优点:便于插入和删除 。
- 缺点:基于数组的操作。不便于扩充容量。
- 数据的存放形式是键值对形式:(key, value)
- 测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace HashTable
{
class Program
{
static void Main(string[] args)
{
//哈希表是一种数据类型
//HashTable---优点:便于插入和删除 缺点:基于数组的操作。不便于扩充容量
Hashtable ht = new Hashtable(); //从哈希表的class里面new对象
ht.Add("1","校长"); //用key--value的方式添加元素 Add()方法
ht.Add("2", "学生");
ht.Add("3", "老师");
ht.Add("4", "教导主任");
string str = ht["2"].ToString(); //通过key调用哈希表的元素
Console.WriteLine(str);
//****************************移除一个元素***************************************************
ht.Remove("3");
//****************************哈希表的遍历***************************************************
//遍历值
foreach (var item in ht.Values)
{
Console.WriteLine(item);
}
//遍历键
foreach (var item in ht.Keys)
{
Console.WriteLine(item);
}
//遍历哈希表
foreach (DictionaryEntry item in ht)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
Console.ReadKey();
}
}
}
- 测试结果: