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 HybridDictionary in C#
To get an ICollection containing the keys in HybridDictionary, you use the Keys property. The HybridDictionary class is part of the System.Collections.Specialized namespace and provides a collection that uses a ListDictionary for small collections and switches to a Hashtable for larger collections automatically.
The Keys property returns an ICollection that contains all the keys in the dictionary, which can then be iterated over or copied to an array.
Syntax
Following is the syntax for accessing the Keys property −
ICollection keys = hybridDictionary.Keys;
To copy keys to an array −
string[] keysArray = new string[hybridDictionary.Count]; hybridDictionary.Keys.CopyTo(keysArray, 0);
Using Keys.CopyTo() Method
The following example demonstrates copying keys to an array using the CopyTo() method −
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict = new HybridDictionary();
dict.Add("One", "Katie");
dict.Add("Two", "Andy");
dict.Add("Three", "Gary");
dict.Add("Four", "Mark");
dict.Add("Five", "Marie");
dict.Add("Six", "Sam");
dict.Add("Seven", "Harry");
dict.Add("Eight", "Kevin");
dict.Add("Nine", "Ryan");
String[] strArr = new String[dict.Count];
dict.Keys.CopyTo(strArr, 0);
Console.WriteLine("Keys in HybridDictionary:");
for (int i = 0; i < dict.Count; i++)
Console.WriteLine(strArr[i]);
}
}
The output of the above code is −
Keys in HybridDictionary: Eight Seven Four Three One Five Six Two Nine
Using foreach with Keys Collection
You can also iterate directly over the Keys collection using a foreach loop −
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict = new HybridDictionary();
dict.Add("1", "A");
dict.Add("2", "B");
dict.Add("3", "C");
dict.Add("4", "D");
dict.Add("5", "E");
dict.Add("6", "F");
Console.WriteLine("Keys using foreach:");
foreach (string key in dict.Keys) {
Console.WriteLine(key);
}
Console.WriteLine("\nTotal number of keys: " + dict.Keys.Count);
}
}
The output of the above code is −
Keys using foreach: 1 2 3 4 5 6 Total number of keys: 6
Key Properties of HybridDictionary.Keys
| Property | Description |
|---|---|
| Count | Gets the number of keys in the collection |
| IsReadOnly | Always returns true for the Keys collection |
| IsSynchronized | Returns false unless the HybridDictionary is synchronized |
Conclusion
The Keys property of HybridDictionary provides an ICollection containing all keys in the dictionary. You can access these keys by copying them to an array using CopyTo() or iterate through them directly using a foreach loop for flexible key manipulation.
