Lesson 3
Diving into Sorted Dictionaries in C#
Diving into Sorted Dictionaries in C#

Hello again! This lesson's topic is Sorted Dictionaries. Similar to other dictionary structures, Sorted Dictionaries store key-value pairs but in an ordered manner. Learning about Sorted Dictionaries enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Sorted Dictionaries using C#'s SortedDictionary class.

Introduction: Sorted Dictionaries in C#

In C#, we differentiate between regular dictionaries like Dictionary and Sorted Dictionaries. Comparing Dictionary to SortedDictionary is akin to comparing a messy bookshelf to a well-organized library — the latter maintains order. Dictionary does not guarantee any order of keys, whereas SortedDictionary sorts the keys in natural order (if they implement the IComparable interface) or according to a specified comparator.

The SortedDictionary class is part of the System.Collections.Generic namespace and provides a binary search tree-based implementation of the IDictionary<TKey, TValue> interface. This ensures that the dictionary is always sorted according to the natural ordering of its keys or by a custom comparator.

Discovering SortedDictionary

To create a SortedDictionary object, you can either use the default constructor or initialize it with a dictionary. The keys used in a SortedDictionary must be immutable and comparable. For instance:

C#
1using System; 2using System.Collections.Generic; 3 4public class SortedDictionaryExample 5{ 6 public static void Main(string[] args) 7 { 8 // SortedDictionary with fruits as keys and corresponding counts as values 9 SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>(); 10 sortedDict["banana"] = 3; 11 sortedDict["apple"] = 4; 12 sortedDict["pear"] = 1; 13 sortedDict["orange"] = 2; 14 15 // Print the SortedDictionary 16 foreach (var item in sortedDict) 17 { 18 Console.WriteLine($"{item.Key}={item.Value}"); 19 } 20 } 21}

The output will be:

1apple=4 2banana=3 3orange=2 4pear=1

In this example, the keys are sorted in alphabetical order. This means that "apple" comes first because 'a' is earlier in the alphabet than 'b' from "banana", 'o' from "orange", and 'p' from "pear". Conversely, "pear" is the greatest key because 'p' has a higher ASCII value than 'a', 'b', and 'o'.

Traversing SortedDictionary Methods

A SortedDictionary object boasts several useful methods. Here are some crucial ones:

  • sortedDict.ContainsKey(key): This returns true if the SortedDictionary contains the specified key.
  • sortedDict.Remove(key): This removes the entry for the specified key if it is present and returns true if the element is successfully found and removed; otherwise, false.
  • sortedDict.TryGetValue(key, out value): This returns true if the dictionary contains an element with the specified key, and value is assigned the value of the key-value pair; otherwise, false.
  • sortedDict.Last(): This returns the last key-value pair in the dictionary.

Consider the following C# code, which incorporates these methods:

C#
1using System; 2using System.Collections.Generic; 3using System.Linq; 4 5public class SortedDictionaryMethods 6{ 7 public static void Main(string[] args) 8 { 9 // Initialize SortedDictionary 10 SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>(); 11 sortedDict["banana"] = 3; 12 sortedDict["apple"] = 4; 13 sortedDict["pear"] = 1; 14 sortedDict["orange"] = 2; 15 16 // Check if 'apple' exists 17 if (sortedDict.ContainsKey("apple")) 18 { 19 Console.WriteLine("Contains 'apple' key: True"); 20 } 21 22 // Remove 'apple' and check removal 23 bool isRemoved = sortedDict.Remove("apple"); 24 Console.WriteLine("Removed 'apple': " + isRemoved); // Output: True 25 26 // Attempt to fetch a non-existing key 27 if (!sortedDict.TryGetValue("apple", out int value)) 28 { 29 Console.WriteLine("Value: Not found"); // Output: Value: Not found 30 } 31 32 // Get the last key-value pair using LINQ 33 var lastEntry = sortedDict.Last(); 34 Console.WriteLine($"Last entry: {lastEntry.Key}={lastEntry.Value}"); // Output: pear=1 35 } 36}
Lesson Summary

Congratulations! You have successfully delved into Sorted Dictionaries. This exploration included understanding the SortedDictionary class, creating SortedDictionary instances, and navigating SortedDictionary's valuable methods. Next, you can look forward to hands-on exercises to fortify your understanding and expand your skill set. Keep practicing!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.