Hashtable 类的实用方法 BuildGlossary方法

来源:互联网 发布:贝叶斯分类器 vb.net 编辑:程序博客网 时间:2024/05/23 18:48


Hashtable 类的实用方法。
(1).Count 属性存储着散列表内元素的数量,它会返回一个整数。

(2).Clear 方法可以立刻从散列表中移除所有元素。

(3).Remove 方法会取走关键字,而且该方法会把指定关键字和相关联的数值都移除。

(4).ContainsKey 方法查看该元素或者数值是否在散列表内。

3.Hashtable 的应用程序。程序首先从一个文本文件中读入一系列术语和定义。这个过程是在子程序BuildGlossary 中编码实现的。文本文件的结构是:单词,定义,用逗号在单词及其定义之间进行分隔。这个术语表中的每一个单词都是单独一个词,但是术语表也可以很容易地替换处理短语。这就是用逗号而不用空格作分隔符的原因。此外,这种结构允许使用单词作为关键字,这是构造这个散列表的正确方法。另一个子程序DisplayWords 把单词显示在一个列表框内,所以用户可以选取一个单词来获得它的定义。既然单词就是关键字,所以能使用Keys 方法从散列表中正好返回单词。然后,用户就可以看到有定义的单词了。用户可以简单地点击列表框中的单词来获取其定义。用Item 方法就可以取回定义,并且把它显示在文本框内。

// 吴新强 实验小结 2013年3月16日22:00:45

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Collections;
  9. using System.IO ;
  10. namespace WindowsApplication3
  11. {
  12. public partial class Form1 : Form
  13. {
  14. private Hashtable glossary = new Hashtable();
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. private void Form1_Load(object sender, EventArgs e)
  20. {
  21. BuildGlossary(glossary);
  22. DisplayWords(glossary);
  23. }
  24. private void BuildGlossary(Hashtable g)
  25. {
  26. StreamReader inFile;
  27. string line;
  28. string[] words;
  29. inFile = File.OpenText(@"c:\words.txt ");
  30. char[] delimiter = newchar[] { ',' };
  31. while (inFile.Peek() != -1)
  32. {
  33. line = inFile.ReadLine();
  34. words = line.Split(delimiter);
  35. g.Add(words[0], words[1]);
  36. }
  37. inFile.Close();
  38. }
  39. private void DisplayWords(Hashtable g)
  40. {
  41. Object[] words = new Object[100];
  42. g.Keys.CopyTo(words, 0);
  43. for (int i = 0; i <= words.GetUpperBound(0); i++)
  44. if (!(words[i] == null))
  45. lstWords.Items.Add((words[i]));
  46. }
  47. private void lstWords_SelectedIndexChanged(object sender, EventArgs e)
  48. {
  49. Object word;
  50. word = lstWords.SelectedItem;
  51. txtDefinition.Text = glossary[word].ToString();
  52. }
  53. }
  54. }  
原创粉丝点击