4.Hashtable類
哈希表,名-值對。類似於字典(比數組更強大)。哈希表是經過優化的,訪問下標的對象先散列過。如果以任意類型鍵值訪問其中元素會快於其他集合。GetHashCode()方法返回一個int型數據,使用這個鍵的值生成該int型數據。哈希表獲取這個值最後返回一個索引,表示帶有給定散列的數據項在字典中存儲的位置。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
...{
class Program
...{
public static void Main()
...{
// Creates and initializes a new Hashtable.
Hashtable myHT = new Hashtable();
myHT.Add("one", "The");
myHT.Add("two", "quick");
myHT.Add("three", "brown");
myHT.Add("four", "fox");
// Displays the Hashtable.
Console.WriteLine("The Hashtable contains the following:");
PrintKeysAndValues(myHT);
}
public static void PrintKeysAndValues(Hashtable myHT)
...{
foreach (string s in myHT.Keys)
Console.WriteLine(s);
Console.WriteLine(" -KEY- -VALUE-");
foreach (DictionaryEntry de in myHT)
Console.WriteLine(" {0}: {1}", de.Key, de.Value);
Console.WriteLine();
}
}
}
圖4
5.SortedList類
與哈希表類似,區別在於SortedList中的Key數組排好序的。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
...{
class Program
...{
public static void Main()
...{
SortedList sl = new SortedList();
sl["c"] = 41;
sl["a"] = 42;
sl["d"] = 11;
sl["b"] = 13;
foreach (DictionaryEntry element in sl)
...{
string s = (string)element.Key;
int i = (int)element.Value;
Console.WriteLine("{0},{1}",s,i);
}
}
}
}
圖5
6.NameValueCollection類
官方給NameValueCollection定義為特殊集合一類,在System.Collections.Specialized下。
System.Collections.Specialized下還有HybridDicionary類,建議少於10個元素用HybridDicionary,當元素增加會自動轉為HashTable。
System.Collections.Specialized下還有HybridDicionary類,字符串集合。
System.Collections.Specialized下還有其他類大家可以各取所需!
言歸正轉主要說NameValueCollection,HashTable 和 NameValueCollection很類似但是他們還是有區別的,HashTable 的KEY是唯一性,而NameValueCollection則不唯一!
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace ConsoleApplication1
...{
class Program
...{
static void Main(string[] args)
...{
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("DdpMDisplaySeq".Trim(), "Display Sequence".Trim());
ht.Add("DdpMNameChi".Trim(), "Name (Chinese)".Trim());
ht.Add("DdpMNameEng".Trim(), "Name (English)".Trim());
ht.Add("Comment".Trim(), "Comment".Trim());
ht.Add("DdpMMarketCode".Trim(), "Market Code".Trim());
foreach (object key in ht.Keys)
...{
Console.WriteLine("{0}/{1}{2},{3}", key, ht[key],
key.GetHashCode(), ht[key].GetHashCode());
}
Console.WriteLine(" ");
NameValueCollection myCol = new NameValueCollection();
myCol.Add("DdpMDisplaySeq".Trim(), "Display Sequence".Trim());
myCol.Add("DdpMNameChi".Trim(), "Name (Chinese)".Trim());
myCol.Add("DdpMNameChi".Trim(), "Name (English)".Trim());
myCol.Add("Comment".Trim(), "Comment".Trim());
myCol.Add("DdpMMarketCode".Trim(), "Market Code".Trim());
foreach (string key in myCol.Keys)
...{
Console.WriteLine("{0}/{1} {2},{3}", key, myCol[key],
key.GetHashCode(), myCol[key].GetHashCode());
}
}
}
}
圖6