注意: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]]