- 哈希表是一種數據類型,跟集合差不多。
- 優點:便於插入和刪除 。
- 缺點:基於數組的操作。不便於擴充容量。
- 數據的存放形式是鍵值對形式:(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();
}
}
}
- 測試結果: