How to access all the elements from the SortedDictionary?

To access elements in a SortedDictionary by key in C#, you can use the indexing operator or the TryGetValue() method. 

Here’s a brief summary of the TryGetValue() method:

  • It attempts to retrieve the value associated with a specified key from the SortedDictionary.
  • If the key is found, the method assigns the corresponding value to the out parameter and returns true.
  • If the key is not found, the out parameter is assigned the default value for its type (e.g., 0 for int) and the method returns false.

Here’s an example:

C#




using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Create a SortedDictionary
        SortedDictionary<string, int> dictionary = new SortedDictionary<string, int>();
 
        // Add some key-value pairs
        dictionary.Add("Apple", 5);
        dictionary.Add("Banana", 3);
        dictionary.Add("Orange", 8);
 
        // Access elements by key using indexing operator
        int appleCount = dictionary["Apple"];
        int orangeCount = dictionary["Orange"];
 
        Console.WriteLine($"Apple count: {appleCount}");   // Output: Apple count: 5
        Console.WriteLine($"Orange count: {orangeCount}"); // Output: Orange count: 8
 
        // Access elements by key using TryGetValue() method
        int bananaCount;
        if (dictionary.TryGetValue("Banana", out bananaCount))
        {
            Console.WriteLine($"Banana count: {bananaCount}"); // Output: Banana count: 3
        }
        else
        {
            Console.WriteLine("Banana not found in the dictionary");
        }
 
        // Accessing an element with a non-existent key will throw a KeyNotFoundException
        // To avoid this, you can use the TryGetValue() method as shown above to check for key existence before accessing the value.
 
        Console.ReadLine();
    }
}


Output

Apple count: 5
Orange count: 8
Banana count: 3

In the above example, we create a SortedDictionary with string keys and integer values. We add some key-value pairs to the dictionary. Then, we access the elements by key using the indexing operator (dictionary[“key”]) and the TryGetValue() method (dictionary.TryGetValue(key, out value)). Finally, we display the retrieved values on the console.

Note that when using the indexing operator, if the specified key does not exist in the SortedDictionary, it will throw a KeyNotFoundException. Therefore, it’s recommended to use the TryGetValue() method when there’s a possibility of the key not existing in the dictionary to handle such scenarios gracefully.

SortedDictionary Implementation in C#

In C#, SortedDictionary is a generic collection that 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 the 
    • 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.

Similar Reads

How to create a SortedDictionary?

A SortedDictionary class has 4 constructors which are used to create a SortedDictionary and the constructors are as follows:...

How to remove elements from the SortedDictionary?

...

How to check the availability of key/value pair in the SortedDictionary?

In SortedDictionary, it is allowed to remove elements from the SortedDictionary. SortedDictionary class provides two different methods to remove elements and the methods are:...

How to access all the elements from the SortedDictionary?

...

How to clear all the elements from the SortedDictionary?

In SortedDictionary, you can check whether the given key or value present in the specified SortedDictionary or not. The SortedDictionary class provides two different methods for checking and the methods are:...

Contact Us