O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.10. Sorting a Hashtable’s Keys and/or Values

Problem

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.

Solution

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required