System.Collections.Hashtable是用來表示一組組key/value結構的容器,可能别的語言會把它叫做Map,Dictionary的,其結構中Key用來快速查找,是以,叫它Dictionary可能更加合适。
Hashtable的方法、屬性并不多,大多數也可以望文生正義,隻是有一點,Hashtable提供了hashTable[aKey]的方式引用其包含的對象,卻并沒有提供數字指向的索引器,就是說用慣了Array,數組的我們,不能用hashTable[0]之類的辦法來檢索它的内容,繼而,我們也就不能用
for(int i =0 ; i < hashTable.count ; i ++)
{
Console.WriteLine("Key -- {0}; Value --{1}.",hashTable[i].key,hashTable[i].value);
}
這樣的代碼塊來周遊,而我們把一個個的鍵值對加入HashTable中,很多情況下都是最終要把它周遊出來,那麼怎麼做呢?以下代碼将解答這個問題。
foreach( DictionaryEntry de in hashTable)
console.WriteLine("Key -- {0}; Value --{1}.", de.Key, de.Value);
不過還是習慣用index來通路的話,System.Collections.Specialized.NameValueCollection是一個可以用index通路的類,不爽的是它的Key/Value都必須是string資料類型。
記得System.Collections.Specialized.ListDictionary是一個單向連結清單的結構,是以如果Key/Value對不多的話,它的效率該比Hashtable高。
System.Collections.Specialized.StringDictionary的話Key是區分大小寫的string資料類型。

Hashtable hash = new Hashtable();

for(int i = 0 ; i < id.Length ; i ++)
{
if(id[i].Trim() != "")
{
string builId = id[i];
string buildept = G.Getxxxx(builId).Rows[0]["xxxx"].ToString().Trim();
if(!hash.Contains(buildept))
hash.Add(buildept,builId);
}
else
hash[buildept] = (string)hash[buildept] + "," + builId;
}
}

foreach(DictionaryEntry de in hash)
string dept = de.Key.ToString().Trim();
string ids = de.Value.ToString().Trim();