Get an ICollection containing keys in OrderedDictionary in C#

The OrderedDictionary class in C# maintains the insertion order of elements. To get an ICollection containing keys from an OrderedDictionary, you can use the Keys property which returns an ICollection object containing all the keys in their insertion order.

Syntax

Following is the syntax to get keys as an ICollection from OrderedDictionary −

OrderedDictionary dict = new OrderedDictionary();
ICollection keys = dict.Keys;

Using Keys Property with CopyTo Method

The most common approach is to use the Keys property and copy the keys to a string array using the CopyTo method −

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("1", "One");
      dict.Add("2", "Two");
      dict.Add("3", "Three");
      dict.Add("4", "Four");
      dict.Add("5", "Five");
      dict.Add("6", "Six");
      dict.Add("7", "Seven");
      dict.Add("8", "Eight");
      
      ICollection col = dict.Keys;
      String[] strKeys = new String[dict.Count];
      col.CopyTo(strKeys, 0);
      
      Console.WriteLine("Displaying the keys...");
      for (int i = 0; i < dict.Count; i++) {
         Console.WriteLine(strKeys[i]);
      }
   }
}

The output of the above code is −

Displaying the keys...
1
2
3
4
5
6
7
8

Using Keys Property with foreach Loop

You can also iterate through the keys collection directly using a foreach loop without copying to an array −

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
   public static void Main() {
      OrderedDictionary dict = new OrderedDictionary();
      dict.Add("One", "John");
      dict.Add("Two", "Tim");
      dict.Add("Three", "Katie");
      dict.Add("Four", "Andy");
      dict.Add("Five", "Gary");
      dict.Add("Six", "Amy");
      
      ICollection col = dict.Keys;
      Console.WriteLine("Displaying the keys...");
      foreach (string key in col) {
         Console.WriteLine(key);
      }
   }
}

The output of the above code is −

Displaying the keys...
One
Two
Three
Four
Five
Six

Key Properties

  • The Keys property returns an ICollection containing all keys in insertion order.

  • Keys are returned as object type, so casting may be required for strongly-typed operations.

  • The collection is read-only and reflects the current state of the OrderedDictionary.

  • Changes to the OrderedDictionary are reflected in the keys collection.

Conclusion

The Keys property of OrderedDictionary returns an ICollection containing all keys in their insertion order. You can either copy these keys to an array using CopyTo method or iterate through them directly using a foreach loop for processing.

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

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements