Light Mode Image

C# SortedList

SortedList is a collection class that represents a collection of key/value pairs that are sorted by the keys.

 

It is part of the System.Collections namespace. Here are some key points about SortedList.

 

Key-Value Pairs

Each element in a SortedList is a key/value pair. The keys must be unique within the collection.

 

Sorted Order

The elements are stored in sorted order based on the keys. When you iterate over the elements of a SortedList, they will be in ascending order according to the keys.

 

Automatic Sorting

SortedList automatically maintains the sorting order as elements are added or removed.

 

Accessing Elements

You can access elements in a SortedList by their key using the indexer, similar to a dictionary.

 

Example of a SortedList in C#.

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        // Creating a new SortedList
        SortedList mySortedList = new SortedList();

        // Adding key/value pairs
        mySortedList.Add("Three", 3);
        mySortedList.Add("One", 1);
        mySortedList.Add("Four", 4);
        mySortedList.Add("Two", 2);

        // Accessing elements by key
        Console.WriteLine("Value for key 'Two': " + mySortedList["Two"]);

        // Iterating over the elements
        foreach (DictionaryEntry entry in mySortedList)
        {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
}

 

In this example, the output will be,

Value for key 'Two': 2
Four: 4
One: 1
Three: 3
Two: 2

 

SortedList is part of the non-generic collections in C#.

 

If you are working with a collection of a specific type, you might want to consider using SortedDictionary<TKey, TValue> or other generic collections available in the System.Collections.Generic namespace.