C# SortedList

The SortedList<TKey, TValue> class in C# is a generic collection that represents a collection of key-value pairs sorted by keys. It is implemented as a combination of an array and a binary search tree, which allows for efficient searching, insertion, and removal operations.

Here’s an example of how to use SortedList<TKey, TValue> in C#:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a new SortedList
        SortedList<int, string> sortedList = new SortedList<int, string>();

        // Add items to the SortedList
        sortedList.Add(3, "Apple");
        sortedList.Add(1, "Banana");
        sortedList.Add(2, "Orange");

        // Access items in the SortedList
        Console.WriteLine(sortedList[1]); // Output: Banana

        // Update an item in the SortedList
        sortedList[2] = "Peach";

        // Remove an item from the SortedList
        sortedList.Remove(3);

        // Iterate over the SortedList
        foreach (KeyValuePair<int, string> kvp in sortedList)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

In the example above, we create a SortedList<int, string> where the keys are integers and the values are strings. We add three key-value pairs to the sorted list, and then demonstrate how to access, update, and remove items using both the key and index-based access. Finally, we iterate over the sorted list to display all the key-value pairs.

The SortedList<TKey, TValue> class provides several methods and properties for working with the sorted list, such as Add, Remove, ContainsKey, ContainsValue, Count, Keys, and Values. It also supports searching for keys and values, as well as performing range-based operations.

Note that the SortedList<TKey, TValue> class maintains the elements in sorted order based on the keys. If you need to preserve the insertion order of elements while still allowing key-based access, you can consider using the SortedDictionary<TKey, TValue> class instead.