Get an ICollection containing the keys in the Hashtable C#

To get an ICollection containing the keys in the Hashtable, you can use the Keys property. The Hashtable.Keys property returns an ICollection object that contains all the keys from the hashtable, which can then be iterated through to access each key.

Syntax

Following is the syntax for accessing keys from a Hashtable −

ICollection keys = hashtable.Keys;

Return Value

The Keys property returns an ICollection containing all the keys in the Hashtable. The order of keys is not guaranteed as Hashtable does not maintain insertion order.

Hashtable Keys Collection Hashtable "A" ? "Electronics" "B" ? "Appliances" "C" ? "Pet Supplies" ICollection Keys "A" "B" "C" .Keys

Using String Keys

Example

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable();
      hash.Add("A", "Electronics");
      hash.Add("B", "Appliances");
      hash.Add("C", "Pet Supplies");
      hash.Add("D", "Books");
      hash.Add("E", "Toys");
      hash.Add("F", "Footwear");
      hash.Add("G", "Clothing");
      
      ICollection col = hash.Keys;
      foreach(string str in col)
         Console.WriteLine(str + ": " + hash[str]);
   }
}

The output of the above code is −

G: Clothing
A: Electronics
B: Appliances
C: Pet Supplies
D: Books
E: Toys
F: Footwear

Using Integer Keys

Example

using System;
using System.Collections;

public class Demo {
   public static void Main() {
      Hashtable hash = new Hashtable();
      hash.Add(1, "AB");
      hash.Add(2, "CD");
      hash.Add(3, "EF");
      hash.Add(4, "GH");
      hash.Add(5, "IJ");
      hash.Add(6, "KL");
      hash.Add(7, "MN");
      
      ICollection col = hash.Keys;
      foreach(int key in col)
         Console.WriteLine("Key = " + key + ", Value = " + hash[key]);
   }
}

The output of the above code is −

Key = 7, Value = MN
Key = 6, Value = KL
Key = 5, Value = IJ
Key = 4, Value = GH
Key = 3, Value = EF
Key = 2, Value = CD
Key = 1, Value = AB

Key Properties

  • The Keys property returns a live collection ? changes to the Hashtable are reflected in the keys collection.

  • Keys are returned in an arbitrary order since Hashtable does not guarantee ordering.

  • The returned ICollection is read-only ? you cannot modify keys through this collection.

  • Each key in the collection is unique, as Hashtable does not allow duplicate keys.

Conclusion

The Hashtable.Keys property provides an efficient way to retrieve all keys as an ICollection, allowing you to iterate through them using foreach loops. Remember that the order of keys is not guaranteed, and the collection reflects live changes to the underlying Hashtable.

Updated on: 2026-03-17T07:04:36+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements