C Sharp SortedDictionary

C# SortedDictionary<TKey, TValue>

The concept of the hashtable is used by the C# SortedDictionary<TKey, TValue> class to store values in ascending order based on key. Found in the System.Collections.Generic namespace, the C# SortedDictionary<TKey, TValue> class contains unique keys only, thus the stored elements can be easily searched or removed using the key.

Example:

using System;  
using System.Collections.Generic;  
 
public class Example  
{  
    public static void Main(string[] args)  
    {  
        SortedDictionary&lt;string, string&gt; countries = new SortedDictionary&lt;string, string&gt;();  
        countries.Add("2","Mexico");    
        countries.Add("5","Japan");    
        countries.Add("1","Canada");    
        countries.Add("4","Nepal");    
        countries.Add("3","India");    
        foreach (KeyValuePair&lt;string, string&gt; i in countries)  
        {  
            Console.WriteLine(i.Key+" "+ i.Value);  
        }  
    }  
}

Output:

Explanation:

In the above example, we are using the generic SortedDictionary<TKey, TValue> class. Here, the Add() method is used to store elements and the for-each loop is used to iterate the elements. To get key and value, the KeyValuePair class is used.

 

Please Share