简介:Hashtable 哈希表,又称散列表,是基于键的哈希代码组织起来的键值对。
本质:Hashtable是C#中封装的一个类,用来处理键值对,即key->value,键值对是配对出现。
功能:提高数据的查询效率。
使用键访问集合中的元素。
特点:1. 键key不可以重复,值value可以重复;2. 通过键查找值,但不能通过值查找键;
声明:需要使用命名空间 using Collections;
Hashtable hashtable = new Hashtable();
增:
//不能出现相同键。
hashtable.Add("key1", "value1");
hashtable.Add(12, 12);
删:
//只能通过键key删除,即删除键,对应的值也会删掉。
hashtable.Remove("key1");
Console.WriteLine(hashtable["key1"]);
//清空
hashtable.Clear();
查:
//通过[键]查看值,找不到返回空null。这里的[]里面放的是键,不是索引下标。
Console.WriteLine(hashtable[1]);
//通过键查找
if (hashtable.Contains(1))
{
Console.WriteLine("存在键为1的键值对");
}
if (hashtable.ContainsKey(1))
{
Console.WriteLine("存在键为1的键值对");
}
//通过值查找
if (hashtable.ContainsValue(3))
{
Console.WriteLine("存在值为3的键值对");
}
改:
//只能修改键对应的值,不能更改键。
hashtable[1] = 12312.2f;
Console.WriteLine(hashtable[1]);
遍历:
//通过Count得到键值对的对数。
Console.WriteLine(hashtable.Count);
//遍历所有键
Console.WriteLine("=======================");
foreach (object item in hashtable.Keys)
{
Console.WriteLine("键:"+item);
Console.WriteLine("值:"+hashtable[item]);
}
//遍历所有值
foreach (object item in hashtable.Values)
{
Console.WriteLine(item);
}
//遍历所有键值对DictionaryEntry
foreach (DictionaryEntry item in hashtable)
{
Console.WriteLine("键:"+item.Key+" "+"值:"+item.Value);
}
//迭代器遍历enumerator
Console.WriteLine("=======================");
IDictionaryEnumerator enumerator = hashtable.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine("键:" + enumerator.Key + " " + "值:" + enumerator.Value);
}
练习题:
using System.Collections;
namespace L4_Hashtable
{
//练习题二:
//制作一个怪物管理器,提供创建怪物,移除怪物的方法。每个怪物都有自己唯一ID。
class Monster
{
public Hashtable monster = new Hashtable();
public void AddMonster(string monsterID,string monsterName)
{
monster.Add(monsterID, monsterName);
}
public void RemoveMonster(string monsterID)
{
monster.Remove(monsterID);
}
}
internal class Program
{
static void Main(string[] args)
{
//练习题一:
//请简述Hashtable的存储规则
//使用键值对存储。
//一个键对应一个值。
//键不能重复,值可以重复。
//能通过键查找值,不能通过值查找键。
//练习题二:
//制作一个怪物管理器,提供创建怪物,移除怪物的方法。每个怪物都有自己唯一ID。
Monster monster = new Monster();
monster.AddMonster("1d2w", "弥诺陶洛斯");
monster.AddMonster("2fdas", "斯芬克斯");
Console.WriteLine(monster.monster["1d2w"]);
Console.WriteLine(monster.monster["2fdas"]);
monster.RemoveMonster("2fdas");
Console.WriteLine(monster.monster["2fdas"]);
}
}
}