C#中HashTable的用法
哈希表(Hashtable)简述
在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,通过哈希函数Key与数组中某一位置相对应,因此key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中keyvalue键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对.
哈希表的简单操作
在哈希表中添加一个keyvalue键值对:HashtableObject.Add(key,value);
在哈希表中去除某个keyvalue键值对:HashtableObject.Remove(key);
从哈希表中移除所有元素: HashtableObject.Clear();
判断哈希表是否包含特定键key: HashtableObject.Contains(key)
哈希表单词查询简单实例
Hashtable hash = new Hashtable();
private void Form1_Load(object sender, EventArgs e)
{
buildhash();
showlist();
}
private void showlist()
{
string[] word=new string[100];
hash.Keys.CopyTo(word,0);
for (int i = 0; i < word.GetUpperBound(0); i++)
{
if (word[i] != null)
{
listBox1.Items.Add(word[i]);
}
}
}
private void buildhash()
{
StreamReader reader;
string line;
string[] words=new string[2];
string path = Application.StartupPath + @"\words.txt";
reader = File.OpenText(path);
char[] chars = new char[] {','};
while (reader.Peek() != -1)
{
line=reader.ReadLine();
words=line.Split(chars);
hash.Add(words[0],words[1]);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string a = hash[listBox1.SelectedItem].ToString();
richTextBox1.Text = a;
}
程序结果: