Understanding and Using C#'s `SortedList`: Efficient Sorted Key-Value Storage

Learn how to utilize C#'s `SortedList` for managing key-value pairs in sorted order. This tutorial explains its functionality, demonstrates adding and iterating through elements, and compares its performance characteristics to `SortedDictionary`, helping you choose the optimal sorted collection for your C# applications.



Understanding C#'s `SortedList` Class

The C# `SortedList` class (part of `System.Collections.Generic`) stores key-value pairs in sorted order based on the key. It combines the features of a list (ordered sequence) and a dictionary (fast key-based lookups). This makes it suitable for situations where you need to maintain a specific order of elements while still being able to quickly access them using a key.

`SortedList` vs. `SortedDictionary`

Both `SortedList` and `SortedDictionary` store sorted key-value pairs. However, they have different performance characteristics:

  • SortedList: Uses less memory but is slower for insertion and deletion of unsorted elements.
  • SortedDictionary: Uses more memory but is faster for insertion and deletion.

Choose `SortedList` when memory usage is a primary concern. Choose `SortedDictionary` when fast insertion and deletion are crucial.

Example: Using `SortedList`

This example demonstrates adding key-value pairs to a `SortedList` and iterating through them using a `foreach` loop:


using System;
using System.Collections.Generic;

public class SortedListExample {
    public static void Main(string[] args) {
        SortedList<string, string> names = new SortedList<string, string>();
        // ... (code to add key-value pairs and iterate using foreach) ...
    }
}

The output shows the key-value pairs sorted by key.