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.Collections.Specialized namespace.

Syntax:

public OrderedDictionary();

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate how
// to create a OrderedDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // od is the OrderedDictionary object
        // OrderedDictionary() is the constructor
        // used to initializes a new
        // instance of the OrderedDictionary class
        OrderedDictionary od = new OrderedDictionary();
  
        // Count property is used to get the
        // number of elements in OrderedDictionary
        // It will give 0 as no elements
        // are present currently
        Console.WriteLine("The number of elements: "
                                           +od.Count);
    }
}

chevron_right


Output:

The number of elements: 0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate how
// to create a OrderedDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // od is the OrderedDictionary object
        // OrderedDictionary() is the constructor
        // used to initializes a new
        // instance of the OrderedDictionary class
        OrderedDictionary od = new OrderedDictionary();
  
        Console.Write("Before Add Method: ");
  
        // Count property is used to get the
        // number of elements in OrderedDictionary
        // It will give 0 as no elements
        // are present currently
        Console.WriteLine(od.Count);
  
        // Adding key/value pairs in od
        od.Add("1", "C");
        od.Add("2", "C++");
        od.Add("3", "Java");
        od.Add("4", "C#");
  
        Console.Write("After Add Method: ");
  
        // Count property is used to get the
        // number of elements in ld
        Console.WriteLine(od.Count);
    }
}

chevron_right


Output:

Before Add Method: 0
After Add Method: 4

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.