Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
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
Keysproperty 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
ICollectionis 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.
