一、業務表分析:
public static void Main(){Hashtable ht = new Hashtable();ht.Add("key1", "value1"); ht.Add("key2", "value2");ht.Add("key3", "value3");ht.Add("key4", "value4"); ht.Add("key5", "value5"); foreach (string str in ht.Keys) {Console.WriteLine(str + ":" + ht[str]);}}
public class NoSortHashTable : Hashtable{private ArrayList list = new ArrayList();public override void Add(object key, object value){base.Add(key, value);list.Add(key);}public override void Clear(){base.Clear();list.Clear();}public override void Remove(object key){base.Remove(key);list.Remove(key);}public override ICollection Keys{get{return list;}}}
注意:ArrayList是不排序的(
public static void Main(){NoSortHashTable ht = new NoSortHashTable();ht.Add("key1", "value1");ht.Add("key2", "value2");ht.Add("key3", "value3");ht.Add("key4", "value4");ht.Add("key5", "value5");foreach (string str in ht.Keys){Console.WriteLine(str + ":" + ht[str]);}}
2.我按Hashtable中鍵的大小順序進行排序
public static void Main(){Hashtable ht = new Hashtable();ht.Add("ee", "value1");ht.Add("dd", "value2");ht.Add("cc", "value3");ht.Add("bb", "value4");ht.Add("aa", "value5");ArrayList list = new ArrayList(ht.Keys);list.Sort();foreach (string str in list){Console.WriteLine(str+":"+ht[str]);}}
3.我按Hashtable中的值得大小就行排序
public static void Main(){Hashtable ht = new Hashtable();ht.Add("a", "3");ht.Add("b", "4");ht.Add("c", "2");ht.Add("d", "1");ArrayList list = new ArrayList(ht.Values);list.Sort();foreach (string svalue in list){IDictionaryEnumerator ide = ht.GetEnumerator();while (ide.MoveNext()){if (ide.Value.ToString() == svalue){Console.WriteLine(ide.Key + ":" + svalue);}}}}
五、總結:
六、重點說明:
public static void Main(){Hashtable hs = new Hashtable(); hs.Add(5, 40); hs.Add(4, 20); hs.Add(3, 20); hs.Add(2, 15); hs.Add(1, 5); ArrayList als = new ArrayList(hs.Values); als.Sort(); foreach (object ob in als) { IDictionaryEnumerator ide = hs.GetEnumerator(); while (ide.MoveNext()) { if (ide.Value.ToString() == ob.ToString()) Console.WriteLine(ide.Key.ToString() + ":" + ob.ToString()); }} }
可以將程式改為:
public static void Main(){Hashtable ht = new Hashtable(); ht.Add(5, 40); ht.Add(4, 20); ht.Add(3, 20); ht.Add(2, 15); ht.Add(1, 5); ArrayList listTemp = new ArrayList(ht.Values); ArrayList list = new ArrayList(); foreach (object value in listTemp) { if (!list.Contains(value)) { list.Add(value); } } list.Sort(); foreach (object obj in list) { IDictionaryEnumerator ide = ht.GetEnumerator(); while (ide.MoveNext()) { if (ide.Value.ToString() == obj.ToString()) { Console.WriteLine(ide.Key.ToString() + ":" + obj.ToString()); } } }}