How to Convert Hashtable into an Array?


The hashtable collection in C# is a non-generic collection of items represented as key-value pairs. Each key is a unique, non-null element. The value on the other hand can be duplicated and/or null.

The Hashtable class in C# represents the hashtable collection. This class provides the relevant methods to create objects, alter items in the collection, etc.

The hashtable collection can be expressed as an array or ArrayList in C#. In this article, let’s discuss how we can convert a hashtable collection into an array.

How to Convert Hashtable into an Array?

To convert the hashtable into an array, the C# Hashtable class provides a method named “CopyTo”. The CopyTo method copies the hashtable items to an array.’

The prototype of the CopyTo method is given below.

Syntax

public virtual void CopyTo (Array array, int arrayIndex);

Parameters

  • array − Destination of the DictionaryEntry objects from the hashtable. This is a one-dimensional array with zero-based indexing.

  • arrayIndex − an integer (Int32) value indicating the zero-based index of the destination array. Represents the position at which copying begins.

Implements

CopyTo(Array, Int32)

Description

Hashtable.CopyTo(Array, Int32) method copies the elements of a Hashtable to a one-dimensional Array instance at the specified index.

Namespace

System.Collections

Exceptions

  • ArgumentNullException − This exception is thrown when the destination array is null.

  • ArgumentOutOfRangeException − thrown if specified arrayIndex is less than zero.

  • ArgumentException − This exception is thrown if the array is multidimensional. OR The hashtable elements to be copied are greater than the available space in the destination array.

  • InvalidCastException − This exception is thrown when there is a type mismatch. i.e. the hashtable type cannot be automatically cast to the destination array type. From the above prototype, we know that the CopyTo method copies the hashtable elements to an array at the specified arrayIndex. The array elements from the specified array index will be overwritten with the hashtable elements.

Now let’s implement a programming example to demonstrate the CopyTo method.

Here we are using the following hashtable.

Key

value

A

FirstValue

B

SecondValue

The above hashtable elements are to be converted to an array. The array is defined as follows.

Index

value

0

She

1

sells

2

sea

3

shells

4

on

5

the

6

sea

7

shore

Example

Now we will copy the hashtable elements into the array starting at index = 6 using the CopyTo method. The entire program for this conversion is given below.

using System;
using System.Collections;
public class MyHashtable {
   public static void Main() {
      // Create and initialize hashtable
      var mySourceHT = new Hashtable();
      mySourceHT.Add("A", "FirstValue");
      mySourceHT.Add("B", "SecondValue");
      
      // Create and initialize the one-dimensional Array.
      var myArray = new String[15];
      myArray[0] = "She";
      myArray[1] = "sells";
      myArray[2] = "sea";
      myArray[3] = "shells";
      myArray[4] = "on";
      myArray[5] = "the";
      myArray[6] = "sea";
      myArray[7] = "shore";

      // Display the array first
      Console.WriteLine("The initial array:");
      PrintValues(myArray, ' ');

      // Use CopyTo method to copy hashtable items to the array at index = 6
      Console.WriteLine("New array after copying hashtable items keys:");
      mySourceHT.Keys.CopyTo(myArray, 6);

      // Display the array values
      PrintValues(myArray, ' ');

      // Use CopyTo method to copy hashtable item values to the array at index
      //= 6
      Console.WriteLine("After copying the values, starting at index 6:");
      mySourceHT.Values.CopyTo(myArray, 6);

      // Display the array values
      PrintValues(myArray, ' ');
   }
   public static void PrintValues(String[] myArr, char mySeparator) {
      for (int i = 0; i < myArr.Length; i++)
         Console.Write($"{mySeparator}{myArr[i]}");
      Console.WriteLine();
   }
}

In this program, we first declare and define the hashtable. Then we declare and define the array. Next, using the CopyTo method we copy the elements of the hashtable to the array starting at index = 6. In this program, first, we copy only the keys of hashtable elements and then we copy the values. The output shows all the states of the array like the initial array, array after copying hashtable elements, etc.

Output

The output of the program is shown below.

The initial array:
   She sells sea shells on the sea shore   
New array after copying hashtable items keys:
   She sells sea shells on the A B     
After copying the values, starting at index 6:
   She sells sea shells on the FirstValue SecondValue 

The above output shows the initial array and then shows the array after copying hashtable keys followed by hashtable values.

Let’s see another example to clearly understand the CopyTo method.

Example

The program is similar to the earlier one. We have changed the hashtable here. Also, we use an empty array for the CopyTo method. The complete program is given below.

using System;
using System.Collections;
class myHashTable {
   public static void Main() {
      // Create a Hashtable named phonetics
      Hashtable phonetics = new Hashtable();
      
      // Add key/value pairs in phonetics
      phonetics.Add("A", "Apple");
      phonetics.Add("B", "Banana");
      phonetics.Add("C", "Cat");
      phonetics.Add("D", "Dog");
      phonetics.Add("E", "Elephant");
      phonetics.Add("F", "Fish");
    
      //print hahshtable collection
      Console.WriteLine("Hashtable items:");
      foreach(DictionaryEntry entry in phonetics){
         Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
      }

      // Create a one-dimensional Array named myArr
      DictionaryEntry[] myArr = new DictionaryEntry[phonetics.Count];

      // copy the Hashtable entries to array using the CopyTo method
      phonetics.CopyTo(myArr, 0);
      Console.WriteLine("Contents of Array after copying hashtable items:");
      for (int i = 0; i < myArr.Length; i++)
         Console.WriteLine(myArr[i].Key + " --> "+ myArr[i].Value);
   }
}

Here we copy all the elements of the hashtable into an empty array using the CopyTo method. Since the array is empty, the elements are copied from the start of the array. Hence we specify the index=0 for the CopyTo method.

Output

The output of the program is given below.

Hashtable items:
B and Banana
C and Cat
A and Apple
F and Fish
D and Dog
E and Elephant
Contents of Array after copying hashtable items:
B --> Banana
C --> Cat
A --> Apple
F --> Fish
D --> Dog
E --> Elephant

In the output, we first display the hashtable and then display the contents of the array. For clarification, the presentation of elements in the hashtable and array is changed.

In this article, we have demonstrated the use of the CopyTo method of the Hashtable class of C# to convert the hashtable items into an array. The CopyTo method accepts the array and the index as arguments, so we can copy the hashtable elements at any part of the array and not necessarily from the beginning. For copying the hashtable elements at the beginning of the array, we specify the index as 0. Depending on the array index specified, the CopyTo method overwrites the array elements, if any, with the hashtable elements.

Updated on: 06-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements