January 2004
Beginner to intermediate
864 pages
22h 18m
English
You want to sort the keys and/or values
contained in a Hashtable in order to display the
entire Hashtable to the user sorted in either
ascending or descending order.
Use the
Keys and
Values properties of a
Hashtable object to obtain an
ICollection of its key
and value objects. The methods shown here return an
ArrayList of objects
containing the keys or values of a
Hashtable:
using System;
using System.Collections;
// Return an ArrayList of Hashtable keys
public static ArrayList GetKeys(Hashtable table)
{
return (new ArrayList(table.Keys));
}
// Return an ArrayList of Hashtable values
public static ArrayList GetValues(Hashtable table)
{
return (new ArrayList(table.Values));
}The following code creates a Hashtable object and
displays first keys, and then values, sorted in ascending and
descending order:
public static void TestSortKeyValues( ) { // Define a hashtable object Hashtable hash = new Hashtable( ); hash.Add(2, "two"); hash.Add(1, "one"); hash.Add(5, "five"); hash.Add(4, "four"); hash.Add(3, "three"); // Get all the keys in the hashtable and sort them ArrayList keys = GetKeys(hash); keys.Sort( ); // Display sorted key list foreach (object obj in keys) Console.WriteLine("Key: " + obj + " Value: " + hash[obj]); // Reverse the sorted key list Console.WriteLine( ); keys.Reverse( ); // Display reversed key list foreach (object obj in keys) Console.WriteLine("Key: " + obj + " Value: " + hash[obj]); // Get all the ...