Hashtable.Keys Property is used to get an ICollection containing the keys in the Hashtable.
Syntax:
CSharp
CSharp
public virtual System.Collections.ICollection Keys { get; }
Return Value: This property returns an ICollection containing the keys in the Hashtable.
Note:
- The order of keys in the ICollection is unspecified.
- Retrieving the value of this property is an O(1) operation.
// C# code to get an ICollection containing
// the keys in the Hashtable.
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("4", "Even");
myTable.Add("9", "Odd");
myTable.Add("5", "Odd and Prime");
myTable.Add("2", "Even and Prime");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
Output:
Example 2:
5: Odd and Prime 9: Odd 2: Even and Prime 4: Even
// C# code to get an ICollection containing
// the keys in the Hashtable.
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("India", "Country");
myTable.Add("Chandigarh", "City");
myTable.Add("Mars", "Planet");
myTable.Add("China", "Country");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
Output:
Reference:
Chandigarh: City India: Country China: Country Mars: Planet