Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Get Hashtable Elements as Sorted Array?
A Hashtable is a non-generic collection of key-value pairs that are arranged according to the hash code of the key. The hashtable optimizes lookups by calculating the hash code of each key and storing it internally. When accessing a particular value, this hash code is matched with the specified key.
This hashtable collection is defined in the System.Collections namespace of C#. The class that represents the hashtable collection is the Hashtable class. By default, hashtable collections are unsorted. To get sorted data, we need to extract the elements into an Array and sort them.
Why Hashtables Are Unsorted
Hashtables store elements based on hash codes for optimal performance. The insertion order and natural sorting are not maintained because elements are placed in buckets determined by their hash values, not their actual content order.
Approach to Get Sorted Array
To get hashtable elements as a sorted array, follow these steps
Create a Hashtable object and populate it with key-value pairs
Create a string array with length equal to the hashtable count
Iterate through the hashtable and copy keys or values to the array
Sort the array using
Array.Sort()
Using Hashtable Keys for Sorting
Example
using System;
using System.Collections;
class Program {
public static void Main() {
// Create a Hashtable
Hashtable langCodes = new Hashtable();
// Add elements to the Hashtable
langCodes.Add("C++", "CPlusPlus");
langCodes.Add("C#", "CSharp");
langCodes.Add("Java", "Java");
langCodes.Add("PL", "Perl");
langCodes.Add("PG", "Prolog");
// Create array of length = hashtable length
string[] sortedArray = new string[langCodes.Count];
// Retrieve key values in Array
int i = 0;
Console.WriteLine("Hashtable langCodes Contents:");
foreach (DictionaryEntry de in langCodes) {
Console.WriteLine("{0} ({1})", de.Key, de.Value);
sortedArray[i] = de.Key.ToString();
i++;
}
Array.Sort(sortedArray);
Console.WriteLine("\nContents of sorted array based on Hashtable keys:");
foreach (var item in sortedArray) {
Console.WriteLine(item);
}
}
}
The output of the above code is
Hashtable langCodes Contents: PG (Prolog) Java (Java) C# (CSharp) PL (Perl) C++ (CPlusPlus) Contents of sorted array based on Hashtable keys: C# C++ Java PG PL
Using Hashtable Values for Sorting
Example
using System;
using System.Collections;
class Program {
public static void Main() {
// Create a Hashtable
Hashtable numberNames = new Hashtable();
// Add elements to the Hashtable
numberNames.Add(12, "Twelve");
numberNames.Add(2, "Two");
numberNames.Add(65, "Sixty Five");
numberNames.Add(15, "Fifteen");
numberNames.Add(18, "Eighteen");
// Create array of length = hashtable length
string[] sortedArray = new string[numberNames.Count];
// Retrieve hashtable values in array
int i = 0;
Console.WriteLine("Hashtable numberNames Contents:");
foreach (DictionaryEntry de in numberNames) {
Console.WriteLine("{0} ({1})", de.Key, de.Value);
sortedArray[i] = de.Value.ToString();
i++;
}
Array.Sort(sortedArray);
Console.WriteLine("\nContents of sorted array based on Hashtable values:");
foreach (var item in sortedArray) {
Console.WriteLine(item);
}
}
}
The output of the above code is
Hashtable numberNames Contents: 18 (Eighteen) 12 (Twelve) 65 (Sixty Five) 2 (Two) 15 (Fifteen) Contents of sorted array based on Hashtable values: Eighteen Fifteen Sixty Five Twelve Two
Alternative Approach Using LINQ
You can also use LINQ to get sorted keys or values more concisely
Example
using System;
using System.Collections;
using System.Linq;
class Program {
public static void Main() {
Hashtable langCodes = new Hashtable();
langCodes.Add("C++", "CPlusPlus");
langCodes.Add("C#", "CSharp");
langCodes.Add("Java", "Java");
langCodes.Add("Python", "Python");
// Get sorted keys using LINQ
var sortedKeys = langCodes.Keys.Cast<string>().OrderBy(x => x).ToArray();
Console.WriteLine("Sorted keys using LINQ:");
foreach (var key in sortedKeys) {
Console.WriteLine(key);
}
// Get sorted values using LINQ
var sortedValues = langCodes.Values.Cast<string>().OrderBy(x => x).ToArray();
Console.WriteLine("\nSorted values using LINQ:");
foreach (var value in sortedValues) {
Console.WriteLine(value);
}
}
}
The output of the above code is
Sorted keys using LINQ: C# C++ Java Python Sorted values using LINQ: CSharp CPlusPlus Java Python
Conclusion
While Hashtable collections are inherently unsorted for performance reasons, you can extract their elements into arrays and sort them using Array.Sort() or LINQ methods. This approach allows you to work with sorted data while maintaining the fast lookup benefits of hashtables for the original collection.
