How to convert a hashtable keys to string array in C#

2 Answers

0 votes
using System;
using System.Collections;

class HashTableToString {
    public static void Main() {
        Hashtable ht = new Hashtable();
      
        ht.Add("A", "C");
        ht.Add("B", "Java");
        ht.Add("C", "Python");
        ht.Add("D", "Go");
        ht.Add("E", "Rust");
        ht.Add("F", "TypeScript");

        string[] keysArray = new string[ht.Keys.Count];
        
        ht.Keys.CopyTo(keysArray, 0);
        
        Console.WriteLine("Keys as String Array:");
        foreach (string key in keysArray) {
            Console.WriteLine(key);
        }
    }
}



/*
run:

Keys as String Array:
D
F
A
E
C
B

*/

 



answered Dec 4, 2025 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections;

class HashTableToString {
    public static void Main() {
        Hashtable ht = new Hashtable();
      
        ht.Add("A", "C");
        ht.Add("B", "Java");
        ht.Add("C", "Python");
        ht.Add("D", "Go");
        ht.Add("E", "Rust");
        ht.Add("F", "TypeScript");

        string[] keysArray = ht.Keys.Cast<string>().ToArray();

        Console.WriteLine("Keys as String Array:");
        foreach (string key in keysArray) {
            Console.WriteLine(key);
        }
    }
}



/*
run:

Keys as String Array:
D
F
A
E
C
B

*/

 



answered Dec 4, 2025 by avibootz

Related questions

...