程序开发 > C# > 正文

C#如何遍历Hashtable及增删注意问题

亮术网 2013-06-01 本网原创

  Hashtable 具有存取方便且速度快的优点,所以常用它来缓存一些常用的数据,比如缓存在线用户、来访IP地址等。用了 Hashtable,就少不了要对它进行遍历。对它进行遍历的方法都有哪些呢?

  Hashtable所在的命名空间为:System.Collections,所以别忘了先 using System.Collections; 。介绍方法前,先新建一个 Hashtable,且添加三个值,具体如下:

 

  Hashtable hashtable = new Hashtable();

  hashtable.Add("01", "User1");
  hashtable.Add("02", "User2");
  hashtable.Add("03", "User3");

 

  1、使用 foreach 循环遍历

  foreach (DictionaryEntry de in hashtable )
  {
    Response.Write("Hashtable 的键为:" + de.Key.ToString());
    Response.Write("Hashtable 的值为:" + de.Value.ToString() + "<br />");
  }

 

  2、使用 while 循环遍历

  IDictionaryEnumerator enumerator = hashtable.GetEnumerator();
  while (enumerator.MoveNext())
  {
    Response.Write("Hashtable 的键为:" + enumerator.Key.ToString());
    Response.Write("Hashtable 的值为:" + enumerator.Value.ToString() + "<br />");
  }

 

  值得注意的是:在遍历过程中,不能对 Hashtable 进行添加和删除操作,否则遍历过程中会产生错误。可以把要删除的健保存到另一个 HashTable 或 数组中,再删除。

本文浓缩标签:Hashtable遍历C#