How to convert a hashtable to string array in C#

1 Answer

0 votes
using System;
using System.Collections;

class HashTableToStringArray
{
    // Function to convert a Hashtable into a string array of "key:value" pairs
    public static string[] ToPairArray(Hashtable ht) {
        string[] pairArray = new string[ht.Count];
        int index = 0;
        
        foreach (DictionaryEntry entry in ht) {
            pairArray[index++] = $"{entry.Key}:{entry.Value}";
        }
        
        return pairArray;
    }

    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[] pairArray = ToPairArray(ht);

        Console.WriteLine("Key-Value Pairs: " + string.Join(", ", pairArray));
    }
}



/*
run:

Key-Value Pairs: D:Go, F:TypeScript, A:C, E:Rust, C:Python, B:Java

*/


 



answered Dec 4, 2025 by avibootz

Related questions

...