
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to Get Hashtable Elements as Sorted Array?
A Hashtable is a non-generic collection of key-value pairs that are arranged as per the hash code of the key. A Hashtable is used to create a collection that uses a hash table for storage. The hashtable optimizes the lookup by calculating the hash code of each key and stores it internally into a basket. When we access the particular value from the hashtable, this hashcode 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. This class provides constructors, methods, and properties to manipulate hashtable collections. By default, the hashtable collection is unsorted. If we want a sorted hashtable collection, we need to represent it in form of an Array or an ArrayList and sort the elements.
In this article, we will see how we can get hashtable elements as a sorted array. So let’s begin.
Get Hashtable elements as Sorted Array
We know that by default, the hashtable collection is unsorted. It can be very difficult to sort the hashtable collection as we create the hashtable collection depending on the keys and then add values to each key.
If we want to sort the hashtable collection, we have to sort it either on keys or values. There is no direct method to sort the hashtable collection in the Hashtable class. So we have to resort to other approaches.
One of the approaches is to get hashtable elements (either keys or values) as a sorted array. For this, we will follow the steps enumerated below.
Create a Hashtable object
Populate this object with key-value pairs
Create an array of type string and length = length of hashtable
Traverse the hashtable based on the keys and populate the array with each key
Sort the generated array
Example
We have programmed this approach using C# which is given below.
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"); int k = langCodes.Count; // create array of length = hashtable length string[] sortedArray = new string[k]; // 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("
Contents of sorted array based on Hashtable keys:"); foreach (var item in sortedArray) { Console.WriteLine(item); } } }
In this program, we define a Hashtable object langCodes and populate it with key-value pairs. Then we retrieve the length of the hashtable and with this length declare an array “sortedArray”. Next, we traverse through the langCodes hashtable and populate the sorted array object with the key values of the langCodes hashtable.
Then we sort the array using the filter, Array.Sort(sortedArray) and print this sorted array.
Output
The output of the program is given below.
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
From the output, we can see that the hashtable key elements are retrieved as a sorted array of elements.
Now let’s take another example. We use the same approach we discussed above. The only difference is in this example, we will populate the array with the values instead of keys from the hashtable.
Example
Let’s see the complete program in C#.
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"); int k = numberNames.Count; //create array of length = hashtable length string[] sortedArray = new string[k]; // Retrieve hashtable values in array. int i = 0; Console.WriteLine("Hashtable langCodes 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("
Contents of sorted array based on Hashtable values:"); foreach (var item in sortedArray) { Console.WriteLine(item); } } }
This program has a Hashtable object, numberNames. We populate it with numbers and their corresponding number names. By traversing the hashtable we populate the sortedArray with the values. Then we sort the array using Array.Sort() filter and print the sorted array.
Output
The output of the program is shown below.
Hashtable langCodes 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
From the output, we can see that the contents of the array (values from the hashtable) are indeed sorted in alphabetical order. We can easily compare the outputs from the hashtable and the sorted array. In the hashtable, the output is not sorted. The key-value pairs are displayed randomly. While in the array, the output is sorted.
Although it is difficult to sort the hashtable elements, we can do the sorting by expressing hashtable elements as an array. But sorting keys and values at once is not possible. We can either retrieve all the keys in an array or all the values in an array. Then we can sort the array using Array.Sort() filter. We can also convert the hashtable into Arrays or ArrayLists and work on them.
- Related Articles
- Golang program to get the hash elements as a sorted array from the hash collection
- How to store/update Hashtable Elements?
- Copying the Hashtable elements to an Array Instance in C#
- How to Convert Hashtable into an Array?
- Count smaller elements in sorted array in C++
- How to get keys from a HashTable in C#?
- Swift Program to get array elements after N elements
- Golang Program to get array elements after N elements
- How to get index in a sorted array based on iterator function in JavaScript?
- Search elements in a sorted object array in Java
- Print sorted distinct elements of array in C language
- How to get volley elements in array list in android?
- Python program to print sorted number formed by merging all elements in array
- How to Get Value from HashTable Collection in C# using Specified Key
- Count of smaller or equal elements in the sorted array in C++
