The C# SortedDictionary<TKey, TValue> class implements a hashtable mechanism to organize and store data based on keys. It ensures that keys are unique and maintains a sorted order based on the keys. Using the keys, users can efficiently search for or delete elements within the collection. This class is located within the System.Collections.Generic namespace.
C# SortedDictionary__PRESERVE_4__ example
Let's explore a sample implementation of a generic SortedDictionary<TKey, TValue> structure that stores items via the Add function and traverses them using a for-each loop. In this scenario, we utilize the KeyValuePair class to access both the key and the value associated with each element.
Example
using System;
using System.Collections.Generic;
public class SortedDictionaryExample
{
public static void Main(string[] args)
{
SortedDictionary<string, string> names = new SortedDictionary<string, string>();
names.Add("1","Sonoo");
names.Add("4","Peter");
names.Add("5","James");
names.Add("3","Ratan");
names.Add("2","Irfan");
foreach (KeyValuePair<string, string> kv in names)
{
Console.WriteLine(kv.Key+" "+kv.Value);
}
}
}
Output:
Output
1 Sonoo
2 Irfan
3 Ratan
4 Peter
5 James