SortedDictionary Implementation in C# - GeeksforGeeks

29 Mar, 2019
In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need.
Important Points:
The SortedDictionary class implements theICollection<KeyValuePair<TKey, TValue>> InterfaceIDictionary<TKey, TValue> InterfaceIEnumerable<KeyValuePair<TKey, TValue>> InterfaceIEnumerable<T> InterfaceIReadOnlyCollection<KeyValuePair<TKey, TValue>> InterfaceIReadOnlyDictionary<TKey, TValue> InterfaceICollection InterfaceIDictionary InterfaceIEnumerable Interface
ICollection<KeyValuePair<TKey, TValue>> Interface
IDictionary<TKey, TValue> Interface
IEnumerable<KeyValuePair<TKey, TValue>> Interface
IEnumerable<T> Interface
IReadOnlyCollection<KeyValuePair<TKey, TValue>> Interface
IReadOnlyDictionary<TKey, TValue> Interface
ICollection Interface
IDictionary Interface
IEnumerable Interface
In SortedDictionary, the key must be unique. Duplicate keys are not allowed.
In SortedDictionary, the keys are immutable and cannot be null.
In SortedDictionary, the value can be null when the type of the value is of reference type.
It provides fastest insertion and removal operations for unsorted data.
In SortedDictionary, you can only store the same types of key/value pairs.
The capacity of a SortedDictionary is the number of key/value pairs that SortedDictionary can hold.
It sort in ascending order.
A SortedDictionary class has 4 constructors which are used to create a SortedDictionary and the constructors are as follows:
SortedDictionary<TKey, TValue>(): This constructor is used to create an instance of the SortedDictionary class that is empty and uses the default IComparer implementation for the key type.
SortedDictionary<TKey, TValue>(IComparer): This constructor is used to create an instance of the SortedDictionary class that is empty and uses the specified IComparer implementation to compare keys.
SortedDictionary<TKey, TValue>(IDictionary): This constructor is used to create an instance of the SortedDictionary class that contains elements copied from the specified IDictionary and uses the default IComparer implementation for the key type.
SortedDictionary<TKey, TValue>(IDictionary, IComparer): This constructor is used to create an instance of the SortedDictionary class that contains elements copied from the specified IDictionary and uses the specified IComparer implementation to compare keys.
Let’s see how to create a SortedDictionary using SortedDictionary<TKey, TValue>() constructor:
Step 1: Include System.Collection.Generics namespace in your program with the help of using keyword.
using System.Collection.Generics;
Step 2:Create a SortedDictionary using SortedDictionary<TKey, TValue> class as shown below:
SortedDictionary<Type_of_key, Type_of_value> sorteddictionary_name = new SortedDictionary<Type_of_key, Type_of_value>();
Step 3: If you want to add elements in your SortedDictionary then use Add() method to add a key/value pairs in your SortedDictionary. And you can also add key/value pair in the SortedDictionary using Collection Initializer.
Step 4: The key/value pair of the SortedDictionary is accessed by using a foreach loop, or by using index value, or by using for loop.
Example:
// C# program to illustrate how // to create sorted dictionaryusing System;using System.Collections.Generic;  class GFG {      // Main Method    static public void Main()    {          // Creating sorted dictionary        // Using SortedDictionary class        SortedDictionary<int, string> My_sdict =             new SortedDictionary<int, string>();          // Adding key/value pair in Sorted         // Dictionary Using Add() method        My_sdict.Add(004, "Ask.com");        My_sdict.Add(003, "Yahoo");        My_sdict.Add(001, "Google");        My_sdict.Add(005, "AOL.com");        My_sdict.Add(002, "Bing");        Console.WriteLine("Top Search Engines:");          // Accessing the key/value pair of the         // SortedDictionary Using foreach loop        foreach(KeyValuePair<int, string> pair in My_sdict)        {            Console.WriteLine("Rank: {0} and Name: {1}",                                  pair.Key, pair.Value);        }          // Creating another sorted dictionary        // using SortedDictionary<TKey, TValue> class        // adding key/value pairs        // Using collection initializer        SortedDictionary<int, string> My_sdict1 =               new SortedDictionary<int, string>() {                                     {1, "Python"},                                      {5, "Swift"},                                 {2, "JavaScript"},                                        {4, "Go" },                                      {3, "Rust"}};                    Console.WriteLine("Top Programming Language in 2019: ");          // Accessing the key/value pair of the         // SortedDictionary Using foreach loop        foreach(KeyValuePair<int, string> pair in My_sdict1)        {            Console.WriteLine("Rank:{0} and Name: {1}",                                 pair.Key, pair.Value);        }    }}
Top Search Engines:
Rank: 1 and Name: Google
Rank: 2 and Name: Bing
Rank: 3 and Name: Yahoo
Rank: 4 and Name: Ask.com
Rank: 5 and Name: AOL.com
Top Programming Language in 2019: 
Rank:1 and Name: Python
Rank:2 and Name: JavaScript
Rank:3 and Name: Rust
Rank:4 and Name: Go
Rank:5 and Name: Swift

In SortedDictionary, it is allowed to remove elements from the SortedDictionary. SortedDictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:
Clear(): This method is used to remove all elements from the SortedDictionary.
Remove(TKey): This method is used to remove the element with the specified key from the SortedDictionary.
Example:
// C# program to illustrate how to// Remove key/value pair from the // SortedDictionaryusing System;using System.Collections.Generic;  class GFG {      // Main Method    static public void Main()    {          // Creating sorted dictionary        // Using SortedDictionary class        SortedDictionary<int, string> My_sdict =              new SortedDictionary<int, string>();          // Adding key/value pair in         // SortedDictionary Using         // the Add() method        My_sdict.Add(001, "Google");        My_sdict.Add(002, "Bing");        My_sdict.Add(003, "Yahoo");        My_sdict.Add(004, "Ask.com");        My_sdict.Add(005, "AOL.com");          // Initial number of key/value pairs        Console.WriteLine("Key/Value pair: {0}",                                My_sdict.Count);          // After using Remove(TKey) method        My_sdict.Remove(002);        Console.WriteLine("Key/Value pair: {0}",                                My_sdict.Count);          // After using Clear() method        My_sdict.Clear();        Console.WriteLine("Key/Value pair: {0}",                                My_sdict.Count);    }}
Key/Value pair: 5
Key/Value pair: 4
Key/Value pair: 0

In SortedDictionary, you can check whether the given key or value present in the specified SortedDictionary or not. The SortedDictionary<TKey, TValue> class provides two different methods for checking and the methods are:
ContainsKey(TKey): This method is used to determine whether the SortedDictionary contains an element with the specified key.
ContainsValue(TValue): This method is used to determine whether the SortedDictionary contains an element with the specified value.
Example:
// C# program to illustrate how to// check the given key/value pair // is exists or not in SortedDictionaryusing System;using System.Collections.Generic;  class GFG {      // Main Method    static public void Main()    {          // Creating sorted dictionary        // Using SortedDictionary class        SortedDictionary<int, string> My_sdict =             new SortedDictionary<int, string>();          // Adding key/value pair         // in SortedDictionary        // Using Add() method        My_sdict.Add(001, "Google");        My_sdict.Add(002, "Bing");        My_sdict.Add(003, "Yahoo");        My_sdict.Add(004, "Ask.com");        My_sdict.Add(005, "AOL.com");          // Using ContainsKey(TKey) method        if (My_sdict.ContainsKey(004) == true)         {            Console.WriteLine("Key Found..");        }        else        {            Console.WriteLine("Key Not Found..");        }          // Using ContainsValue(TValue) method        if (My_sdict.ContainsValue("Baidu") == true)        {            Console.WriteLine("Value Found..");        }          else         {            Console.WriteLine("Value Not Found..");        }    }}
Key Found..
Value Not Found..

CSharp SortedDictionary Class
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
String.Split() Method in C# with Examples
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# | Delegates
C# | Arrays of Strings
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1