07 Feb 2024




Intermediate

SortedList<K, V> Generic Collections in C#

Definition:

SortedList<K, V> is a generic collection class in the System.Collections.Generic namespace of C#. It represents a collection of key-value pairs that are sorted by keys. The keys must be unique and must be immutable. The K represents the type of keys, and V represents the type of values stored in the sorted list.

Key Features and Characteristics:

  • Sorted Order: SortedList<K, V> maintains the elements sorted by their keys in ascending order.
  • Generic Type Parameters: SortedList<K, V> is generic, allowing it to store elements of any data type specified by the developer for both keys and values.
  • Efficient Lookup: Provides efficient lookup times for retrieving values based on their corresponding keys using binary search.
  • Automatic Sorting: Automatically maintains the sorted order of elements based on the keys, ensuring that the keys are always in ascending order.
  • Array-based Implementation: Internally, SortedList<K, V> uses an array-based data structure to maintain the sorted order of elements.
  • Methods and Properties: SortedList<K, V> provides a variety of methods and properties for adding, removing, and accessing elements. Some common methods include Add, Remove, ContainsKey, TryGetValue, Keys, Values, Clear, and more.

Uses:

  • Maintaining a collection of key-value pairs in sorted order.
  • Efficiently looking up values based on their corresponding keys.
  • Implementing sorted dictionaries, maps, or associative arrays in algorithms and data structures.

Advantages:

  • Provides fast lookup times based on binary search, even for large collections.
  • Automatically maintains the sorted order of elements, eliminating the need for manual sorting.
  • Supports generic types, allowing for flexibility in the types of keys and values stored.
  • Efficient for scenarios requiring frequent retrieval of elements based on keys.

Disadvantages:

  • Higher memory overhead compared to unsorted dictionaries due to the additional bookkeeping required for maintaining the sorted order.
  • Slower insertion and removal operations compared to unsorted dictionaries due to the additional sorting overhead.

Code Example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Creating a SortedList with int keys and string values
        SortedList<int, string> students = new SortedList<int, string>();

        // Adding key-value pairs to the SortedList
        students.Add(102, "Alice");
        students.Add(105, "Bob");
        students.Add(101, "Charlie");

        // Retrieving and displaying the name of a specific student
        if (students.ContainsKey(105))
        {
            string studentName = students[105];
            Console.WriteLine("Student with ID 105: " + studentName); // Output: Student with ID 105: Bob
        }

        // Iterating over the key-value pairs in sorted order
        foreach (var kvp in students)
        {
            Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
        }
    }
}

Explanation: This example demonstrates creating a SortedList<int, string> and adding key-value pairs to it. The Add method is used to add elements to the sorted list. The ContainsKey property is used to check if a key exists before accessing its value. The foreach loop is used to iterate over all key-value pairs in the sorted list, which are automatically sorted by keys in ascending order, and print them.

c-sharp
sortedlist
generic-collections