- using System;
- using System.Collections.Generic;
- using System.Collections;
- using System.Linq;
- using System.Text;
- namespace HDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Hashtable ht = new Hashtable();
- #region HashTabel常用方法
- ht.Add("姓名", "XO");//添加key/键值对
- ht.Add("年龄", "21");
- ht.Add("职业", "SoftwareEngineer");
- ht.Add("性别", "Female");
- ht.Add("sex", "1");
- ht.Add("编号", "001");
- Int32 age = Convert.ToInt32(ht["sex"]);//用Int转换会出错
- bool isExist = ht.ContainsKey("性别");//判断哈希表是否包含特定键,其返回值为true或false
- ht.Remove("sex");//移除一个key/键值对
- // ht.Clear();//移除所有元素
- Console.WriteLine(" --- HashTabel常用方法 ---");
- Console.WriteLine(ht.Count.ToString());
- Console.WriteLine(isExist.ToString());
- Console.WriteLine(age.ToString());
- Console.WriteLine(" ");
- Console.WriteLine("/* ********************************** */");
- Console.WriteLine(" ");
- #endregion
- #region 判定速度比较
- Console.WriteLine(" --- HashTabel的判定试试比较 ---");
- if (ht.ContainsKey("姓名"))
- {
- Console.WriteLine(ht["姓名"].ToString());
- }
- object value = ht["姓名"];
- if (value != null)
- {
- Console.WriteLine(value.ToString());
- }
- Console.WriteLine(" ");
- Console.WriteLine("/* ********************************** */");
- Console.WriteLine(" ");
- #endregion
- #region 遍历哈希表
- Console.WriteLine(" --- 遍历哈希表 --- ");
- foreach (DictionaryEntry de in ht)
- {
- Console.WriteLine(de.Key + " : " + de.Value);
- }
- Console.WriteLine(" ");
- Console.WriteLine("/* ********************************** */");
- Console.WriteLine(" ");
- #endregion
- #region 对哈希表进行排序
- //无法直接在Hashtable进行对key进行重新排列.采用变通的方法
- ArrayList akeys = new ArrayList(ht.Keys); //别忘了导入System.Collections
- akeys.Sort(); //按字母顺序进行排序
- Console.Write(" --- 对哈希表进行排序 --- ");
- Console.WriteLine("");
- foreach (string skey in akeys)
- {
- Console.Write(skey + ":");
- Console.WriteLine(ht[skey]);//排序后输出
- }
- #endregion
- #region 简介
- Console.WriteLine(" ");
- Console.WriteLine("/* ********************************** */");
- Console.WriteLine(" ");
- Console.Write(" --- 哈希表简介 --- ");
- Console.WriteLine(" ");
- Console.WriteLine("在.NET work中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似key/的键值对,其中key通常可用来快速查找,同时key是区分大小写;用于存储对应于key的值。Hashtable中key/键值对均为object类型,所以Hashtable可以支持任何类型的key/键值对.");
- #endregion
- Console.Read();
- }
- }
- }
以前没太注意它,使用的时候就出了错:
相关内容:Js中HashTable的应用;
HashTable与其它的相似与区别;如(ArrayList/DataTabel)