注意:Hashtable 按鍵的正序排列鍵/值對,預設情況下的遍曆GetValues是逆序遍曆。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace HashtableSort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("+++++++++++對HashTable排序測試+++++++++++");
HashTable htb = new HashTable();
htb.Add(1, "1");
htb.Add(3, "3");
htb.Add(0, "0");
htb.Add(2, "2");
htb.Add(7, "7");
htb.Add(6, "6");
htb.Add(8, "8");
htb.Add(10, "10");
htb.Add(9, "9");
htb.Add(11, "11");
htb.GetValues();
htb.GetInfo();
htb.AscSort();
htb.DescSort();
}
}
class HashTable
{
Hashtable htb;
public HashTable()
{
htb = new Hashtable();
}
//添加鍵/值對
public void Add(object key, object value)
{
htb.Add(key, value);
Console.WriteLine(string.Format("向Hashtable中添加了/t鍵{0},值{1}", key, value));
}
//遍曆Hsahtbale
public void GetValues()
{
Console.WriteLine("+++++++++++遍曆Hsahtbale開始+++++++++++");
foreach(DictionaryEntry de in htb)
{
Console.WriteLine("當前Hashtable中的鍵/值對:/t鍵:{0},值:{1}",de.Key,de.Value);
}
Console.WriteLine("+++++++++++遍曆Hsahtbale結束+++++++++++");
}
//得到Hashtable資訊
public void GetInfo()
{
Console.WriteLine("Hashtable中有鍵/值對{0}對", htb.Count);
}
//對HashTable排序
public void AscSort()
{
Console.WriteLine("+++++++++++對HashTable正序排序開始+++++++++++");
ArrayList arrList = new ArrayList(htb.Keys);
arrList.Sort();
//for (int i = 0; i < arrList.Count; i++)
//{
// Console.WriteLine("/t鍵{0}", arrList[i]);
//}
for (int i = 0; i < arrList.Count; i++)
{
Console.WriteLine(string.Format("/t鍵:{0}的值是:{1}", arrList[i], htb[arrList[i]]));
}
Console.WriteLine("+++++++++++對HashTable正序排序結束+++++++++++");
}
public void DescSort()
{
Console.WriteLine("+++++++++++對HashTable逆序排序開始+++++++++++");
ArrayList arrList = new ArrayList(htb.Keys);
arrList.Sort();
//for (int i = 0; i < arrList.Count; i++)
//{
// Console.WriteLine("/t鍵{0}", arrList[i]);
//}
for (int i = arrList.Count-1; i >= 0; i--)
{
Console.WriteLine(string.Format("/t鍵:{0}的值是:{1}", arrList[i], htb[arrList[i]]));
}
Console.WriteLine("+++++++++++對HashTable逆序排序結束+++++++++++");
}
}
}
有特點的幾處:arrList[i], htb[arrList[i]]