C#中的哈希表(HashTable)是由一些列哈希代码组构起的键值对,用于提高访问元素的效率,可以使用键来访问值,键和值都属于Object类型的变量,它同样提供增删查改和多种遍历操作。
cs
using System;
using System.Collections;
namespace lesson04
{
class Program
{
static void Main(string[] args)
{
Hashtable hashtable = new Hashtable();
#region 增删查改
//增加(不允许出现相同的键)
hashtable.Add(1, "123");
hashtable.Add(2, "456");
hashtable.Add(3, "789");
hashtable.Add("999", 45);
//删除
hashtable.Remove(999);
//清空
//hashtable.Clear();
//查找(找不到返回null)
Console.WriteLine(hashtable[3]);
//查找键或值是否在哈希表中
if (hashtable.Contains(2))
{
Console.WriteLine("存在键为2的键值对");
}
if (hashtable.ContainsKey(3))
{
Console.WriteLine("存在键为3的键值对");
}
if (hashtable.ContainsValue("123"))
{
Console.WriteLine("存在键为123的键值对");
}
//修改(仅允许修改值内容)
hashtable[0] = 100.5f;
Console.WriteLine("********************");
#region 遍历
Console.WriteLine(hashtable.Count);
//1,遍历所有键
foreach (object item in hashtable.Keys)
{
Console.WriteLine("键 = " + item);
Console.WriteLine("值 = " +hashtable[item]);//顺带遍历值
}
Console.WriteLine("********************");
//2.遍历所有值
foreach (object item in hashtable.Values)
{
Console.WriteLine("值 = " + item);
}
Console.WriteLine("********************");
//3.同时遍历键值对
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine("键 = " + item.Key + "值 = " + item.Value);
}
//4.迭代器遍历
IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator();
bool flag = myEnumerator.MoveNext();
while (flag)
{
Console.WriteLine("键 = " + myEnumerator.Key + "值 = " + myEnumerator.Value);
flag = myEnumerator.MoveNext();
}
#endregion
#endregion
}
}
}