要了解C#中Hashtable Dictionary的使用
using System;
using System
namespace NoSortHashtable
{
/// <summary>
/// Summary description for Class
/// </summary>
class Class
{
/// <summary>
/// The main entry point for the application
/// </summary>
[STAThread]
static void Main(string[] args)
{
Hashtable hashTable = new Hashtable();
hashTable
hashTable
hashTable
hashTable
foreach(string str in hashTable
{
Console
}
}
}
}
打印的結果是
anhui : hefei
hunan : changsha
sichuan : chengdu
beijing : beijing
為何產生這樣的結果? 我查了MSDN後發現
Hashtable 對象由包含集合元素的存儲桶組成
哈希函數是基於鍵返回數值哈希代碼的算法
在 Hashtable 中用作元素的每一對象必須能夠使用 GetHashCode 方法的實現為其自身生成哈希代碼
在將一個對象添加到 Hashtable 時
例如
Dictionary 類與 Hashtable 類的功能相同
產生這個結果的原因就是Hashtable內部的排序機制使然
google後發現幾個可以解決的辦法
比如
using System;
using System
namespace NoSortHashtable
{
public class NoSortHashtable : Hashtable
{
private ArrayList keys = new ArrayList();
public NoSortHashtable()
{
}
public override void Add(object key
{
base
keys
}
public override ICollection Keys
{
get
{
return keys;
}
}
public override void Clear()
{
base
keys
}
public override void Remove(object key)
{
base
keys
}
public override IDictionaryEnumerator GetEnumerator()
{
return base
}
}
}
或者
只要Compare函數的返回結果不等於
using System;
using System
namespace testSortedList
{
class Class
{
[STAThread]
static void Main(string[] args)
{
SortedList sl = new SortedList(new MySort()); //不排序 [Page]
sl
sl
sl
sl
PrintList(sl);
Console
}
private static void PrintList(SortedList sl)
{
for(int i=
{
Console
}//end for
}//end fn()
}
public class MySort:IComparer
{
#region IComparer 成員
public int Compare(object x
{
return
//排序
// int iResult = (int)x
// if(iResult ==
// return iResult;
}
#endregion
}
}
使用單鏈接列表實現 IDictionary
最後我測試了使用泛類型的Dictionary<T
using System;
using System
using System
using System
namespace NoSortHashtable
{
/// <summary>
/// Summary description for Class
/// </summary>
public class Class
{
/// <summary>
/// The main entry point for the application
/// </summary>
[STAThread]
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht
ht
ht
ht
foreach(string str in ht
{
Console
}
Console
Dictionary<String
dic
dic
dic
dic
foreach(string str in dic
{
Console
}
Console
ListDictionary lsdic = new ListDictionary();
lsdic
lsdic
lsdic
lsdic
foreach(string str in lsdic
{
Console
}
}
}
}
From:http://tw.wingwit.com/Article/program/ASP/201311/21738.html