Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# Dictionary Class
Next article icon

C# OrderedDictionary Class

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, the OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.Collections.Specialized namespace.

  • It implements both IDicitonary and ICollection interfaces.
  • Allows indexed access to elements via both keys and numeric indexes.
  • It provides the ability to iterate over the elements while maintaining the order of insertion.

Example: This example demonstrates how to use the OrderedDictionary class to store and iterate over key-value pairs while maintaining the order in which the elements are added.

C#
// C# program to demonstrates the  // working of OrderedDictionary using System; using System.Collections.Specialized; using System.Collections;   class Geeks {     static void Main()     {         // Create an OrderedDictionary instance         OrderedDictionary od = new OrderedDictionary();          // Add key-value pairs         od.Add("Geek1", 1);         od.Add("Geek2", 2);         od.Add("Geek3", 3);         od.Add("Geek4", 4);          // Iterate through the OrderedDictionary          // and print the key-value pairs         foreach (DictionaryEntry i in od)         {             Console.WriteLine($"{i.Key}: {i.Value}");         }     } } 

Output
Geek1: 1 Geek2: 2 Geek3: 3 Geek4: 4 

Declaration of OrderedDictionary

In C#, the orderedDicitonary class is represented as:

OrderedDictionary orderedDict = new OrderedDictionary();

Constructors

ConstructorsDescription
OrderedDictionary()Initializes a new instance of the OrderedDictionary class.
OrderedDictionary(IEqualityComparer)Initializes a new instance of the OrderedDictionary class using the specified comparer.
OrderedDictionary(Int32)Initializes a new instance of the OrderedDictionary class using the specified initial capacity.
OrderedDictionary(Int32, IEqualityComparer)Initializes a new instance of the OrderedDictionary class using the specified initial capacity and comparer.
OrderedDictionary(SerializationInfo, StreamingContext)Initializes a new instance of the OrderedDictionary class that is serializable using the specified SerializationInfo and StreamingContext objects.

Example: This example demonstrates how to create an OrderedDictionary, add key-vlaue pairs and display the count and key-value while maintaining the insertion order.

C#
// C# program to demosntrate the count and  // key-value pair of OrderedDictionary using System; using System.Collections; using System.Collections.Specialized;  class Geeks {      // Driver method     public static void Main()     {         // Creating a orderedDictionary named myDict         OrderedDictionary od = new OrderedDictionary();          // Adding key and value in myDict         od.Add("1", "ONE");         od.Add("2", "TWO");         od.Add("3", "THREE");          // Displaying the number of key/value         // pairs in myDict         Console.WriteLine("The count is : " + od.Count);          // Displaying the key/value pairs in myDict         foreach(DictionaryEntry i in od)             Console.WriteLine(i.Key + " --> " + i.Value);     } } 

Output
The count is : 3 1 --> ONE 2 --> TWO 3 --> THREE 

Properties

The OrderedDictionary class provides several properties to access its state.

PropertiesDescription
CountGets the number of key/values pairs contained in the OrderedDictionary collection.
IsReadOnlyGets a value indicating whether the OrderedDictionary collection is read-only.
Item[Int32]Gets or sets the value at the specified index.
Item[Object]Gets or sets the value with the specified key.
KeysGets an ICollection object containing the keys in the OrderedDictionary collection.
ValuesGets an ICollection object containing the values in the OrderedDictionary collection.

Example 1: This example checks if the dictionary is read-only using the IsReadOnly property.

C#
// C# code to check if OrderedDictionary  // collection is read-only  using System;  using System.Collections;  using System.Collections.Specialized;   class Geeks {   	public static void Main()  	{  		// Creating a orderedDictionary named myDict  		OrderedDictionary od = new OrderedDictionary();   		// Adding key and value in myDict  		od.Add("key1", "value1");  		od.Add("key2", "value2");  		od.Add("key3", "value3");    		// Checking if OrderedDictionary  		// collection is read-only  		Console.WriteLine(od.IsReadOnly);  	}  }  

Output
False 

Example 2: This example demonstrates the count of key-value pairs using the Count property.

C#
// C# code to get the number of  // key/values pairs contained  // in the OrderedDictionary  using System;  using System.Collections;  using System.Collections.Specialized;   class Geeks {   	public static void Main()  	{   		// Creating a orderedDictionary named myDict  		OrderedDictionary od = new OrderedDictionary();   		// Adding key and value in myDict  		od.Add("1", "Geeks");  		od.Add("2", "for");  		od.Add("3", "Geeks");  		od.Add("4", "C#");   		// To Get the number of key/values  		// pairs contained in the OrderedDictionary  		Console.WriteLine("Number of key-value pairs are : " 											+ od.Count);  	}  }  

Output
Number of key-value pairs are : 4 

Methods

MethodsDescription
Add(Object, Object)Adds an entry with the specified key and value into the OrderedDictionary collection with the lowest available index.
AsReadOnly()Returns a read-only copy of the current OrderedDictionary collection.
Clear()Removes all elements from the OrderedDictionary collection.
Contains(Object)Determines whether the OrderedDictionary collection contains a specific key.
CopyTo(Array, Int32)Copies the OrderedDictionary elements to a one-dimensional Array object at the specified index.
Equals(Object)Determines whether the specified object is equal to the current object.
GetEnumerator()Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.
GetHashCode()Serves as the default hash function.
GetObjectData(SerializationInfo, StreamingContext)Implements the ISerializable interface and returns the data needed to serialize the OrderedDictionary collection.
GetType()Gets the Type of the current instance.
Insert(Int32, Object, Object)Inserts a new entry into the OrderedDictionary collection with the specified key and value at the specified index.
MemberwiseClone()Creates a shallow copy of the current Object.
OnDeserialization(Object)Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.
Remove(Object)Removes the entry with the specified key from the OrderedDictionary collection.
RemoveAt(Int32)Removes the entry at the specified index from the OrderedDictionary collection.
ToString()Returns a string that represents the current object.

Example 1: This example demonstrates how to create an OrderedDictionary, add key-value pairs and obtain a read-only copy of the docitonatry using AsReadOnly().

C#
// C# code to get a read-only  // copy of the OrderedDictionary  using System;  using System.Collections;  using System.Collections.Specialized;   class Geeks {   	public static void Main()  	{  		// Creating a orderedDictionary named myDict  		OrderedDictionary od = new OrderedDictionary();   		// Adding key and value in myDict  		od.Add("key1", "value1");  		od.Add("key2", "value2");  		od.Add("key3", "value3");   		// To Get a read-only copy of  		// the OrderedDictionary  		OrderedDictionary d = od.AsReadOnly();   		// Checking if d is read-only  		Console.WriteLine(d.IsReadOnly);  	}  }  

Output
True 

Example 2: This example demonstrates, how to remove an entry and display the updated count and elements.

C#
// C# code to remove the entry // with the specified key from // the OrderedDictionary using System; using System.Collections; using System.Collections.Specialized;  class Geeks {      public static void Main()     {          // Creating a orderedDictionary named myDict         OrderedDictionary od = new OrderedDictionary();          // Adding key and value in myDict         od.Add("key1", "value1");         od.Add("key2", "value2");         od.Add("key3", "value3");          // Displaying the number of element initially         Console.WriteLine("Number of elements are : "                           + od.Count);          // Displaying the elements in myDict         foreach(DictionaryEntry i in od)             Console.WriteLine(i.Key + " --> " + i.Value);          // Removing the entry with the specified         // key from the OrderedDictionary         od.Remove("key2");          // Displaying the number of element initially         Console.WriteLine("Number of elements are: "                           + od.Count);          // Displaying the elements in myDict         foreach(DictionaryEntry i in od)             Console.WriteLine(i.Key + " -->" + i.Value);     } } 

Output
Number of elements are : 3 key1 --> value1 key2 --> value2 key3 --> value3 Number of elements are: 2 key1 -->value1 key3 -->value3 


Next Article
C# Dictionary Class

S

Sahil_Bansall
Improve
Article Tags :
  • C#
  • CSharp-Specialized-Namespace
  • CSharp-Specialized-OrderedDictionary

Similar Reads

  • C# SortedDictionary Class
    In C#, the SortedDictionary<TKey,TValue> class represents the collection of key/value pairs. This pair is in sorted form and the sorting is done on the key. This class is defined under System.Collections.Generic namespace. In the SortedDictionary class, the keys are immutable, always unique, a
    5 min read
  • C# Dictionary Class
    In C#, the Dictionary class is the part of the System.Collections.Generic namespace. It is a Collection that stores Key-value pairs. Each key in the dictionary is unique and each key maps to a single value. In Dictionary, each entry consists of a key and its associated value.It provides constant tim
    7 min read
  • C# HybridDictionary Class
    In C#, the HybridDictionary Class is the part of the System.Collections.Specialized namespace. It is a collection that combines the features of both a Hashtable and a ListDictionary. It implements a linked list and hash table data structure. It implements IDictionary by using a ListDictionary when t
    6 min read
  • C# StringDictionary Class
    In C#, the StringDictionary class is the part of the System.Collections.Specialized namespace. It is a collection of key-value pairs where the keys are strings and values are objects. It is similar to a Hashtable. But it is specifically designed for use with string keys. Keys are always strings, and
    5 min read
  • C# ListDictionary Class
    In C#, the ListDictionary class is the part of the System.Collections.Specialized namespace. It is a collection that stores key-value pairs. It is used in scenarios where the number of elements is relatively small and the order of insertion needs to be preserved. It uses a single LinkedList to store
    5 min read
  • C# | SortedDictionary.Clear() Method
    This method is used to remove all key/value pairs from the SortedDictionary<TKey, TValue>. Syntax: public void Clear (); Below are the programs to illustrate the use of the above-discussed method: Example 1: // C# code to remove all pairs // from SortedDictionary using System; using System.Col
    2 min read
  • How to create an OrderedDictionary in C#
    OrderedDictionary() constructor is used to initialize a new instance of the OrderedDictionary class which will be empty and will have the default initial capacity. OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.Coll
    2 min read
  • C# | SortedDictionary.Add() Method
    This is used to add a specified key and value to the sorted dictionary. The elements are sorted according to TKey. Syntax: public void Add (TKey key, TValue value); Parameters: key: It is the key of the element to add. value: It is the value of the element to add. The value can be null for reference
    3 min read
  • C# | SortedDictionary.Keys Property
    This property is used to get a collection containing the keys in the SortedDictionary. Syntax: public System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection Keys { get; } Return Value : It returns a collection containing the keys in the SortedDictionary. Below are the programs
    2 min read
  • C# | SortedDictionary.Count Property
    This property is used to get the number of key/value pairs contained in the SortedDictionary<TKey, TValue>. Syntax: public int Count { get; } Return Value : It returns the number of key/value pairs contained in the SortedDictionary. Below are the programs to illustrate the use of above-discuss
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences