Hashtable和Dictionary的使用
由于Hashtable内部自带有排序(根据Key的HashCode来进行的),因此有时在使用Hashtable时就会造成数据顺序不可控的情况,有两种办法可以解决,
测试代码:
Dictionary<string,string> ht=new Dictionary<string, string>(); ht.Add("http://www.sina.com.cn","");
ht.Add("http://www.bjut.edu.cn","");
ht.Add("http://lib.bjut.edu.cn", "");
ht.Add("http://news.bjut.edu.cn", "");
ht.Add("http://sse.bjut.edu.cn", "");
ht.Add("http://lexus.cnblogs.com", "");
ht.Add("http://www.sina.com.cn/sport", "");
ht.Add("http://www.sina.com.cn/ent", "");
foreach(var kvp in ht)
Console.WriteLine(kvp.Key);
Console.WriteLine("============================================");
Hashtable ht2=new Hashtable();
ht2.Add("http://www.sina.com.cn", "");
ht2.Add("http://www.bjut.edu.cn", "");
ht2.Add("http://lib.bjut.edu.cn", "");
ht2.Add("http://news.bjut.edu.cn", "");
ht2.Add("http://sse.bjut.edu.cn", "");
ht2.Add("http://lexus.cnblogs.com", "");
ht2.Add("http://www.sina.com.cn/sport", "");
ht2.Add("http://www.sina.com.cn/ent", "");
foreach(DictionaryEntry i in ht2)
Console.WriteLine(i.Key);
第一种是继承Hashtable,自己创建一个新的类,用一个ArrayList对象保存keys;
代码:(转)
using System;using System.Collections;
namespace NoSortHashtable
}
测试:
hashTable.Add("hunan","changsha");
hashTable.Add("beijing","beijing");
hashTable.Add("anhui","hefei");
hashTable.Add("sichuan","chengdu");
foreach(string str in hashTable.Keys)
{
Console.WriteLine(str + " : " + hashTable[str]);
}
----------------------------------------------------------------------
第二种办法是采用泛型的Dictionary<T,K>对象,该对象按照插入的顺序输出;
Dictionary<string,string> ht=new Dictionary<string, string>(); ht.Add("http://www.sina.com.cn","");
ht.Add("http://www.bjut.edu.cn","");
ht.Add("http://lib.bjut.edu.cn", "");
ht.Add("http://news.bjut.edu.cn", "");
ht.Add("http://sse.bjut.edu.cn", "");
ht.Add("http://lexus.cnblogs.com", "");
ht.Add("http://www.sina.com.cn/sport", "");
ht.Add("http://www.sina.com.cn/ent", "");
foreach(var kvp in ht) Console.WriteLine(kvp.Key);