Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata