Hashtable to array

In this chapter you will learn:

  1. How to convert C# Hashtable to an array

Convert to array

The following code shows how to copy the keys from Hashtable into an array using the CopyTo() method and then display the array contents.

using System;/*from  j a  v  a2s .c o  m*/
using System.Collections;

class MainClass
{

  public static void Main()
  {
    Hashtable myHashtable = new Hashtable();

    myHashtable.Add("AL", "Alabama");
    myHashtable.Add("CA", "California");
    myHashtable.Add("FL", "Florida");
    myHashtable.Add("NY", "New York");
    myHashtable.Add("WY", "Wyoming");

    foreach (string myKey in myHashtable.Keys)
    {
      Console.WriteLine("myKey = " + myKey);
    }
    foreach(string myValue in myHashtable.Values)
    {
      Console.WriteLine("myValue = " + myValue);
    }
    
    Console.WriteLine("Copying keys to myKeys array");
    string[] myKeys = new string[5];
    myHashtable.Keys.CopyTo(myKeys, 0);
    
    for (int counter = 0; counter < myKeys.Length; counter++) {
      Console.WriteLine("myKeys[" + counter + "] = " + myKeys[counter]);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Generic Queue and Non-generic Queue
  2. Clear a Queue
  3. Peek a queue
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack