0
0
CsharpConceptBeginner · 3 min read

What is SortedList in C#: Explanation and Example

SortedList in C# is a collection that stores key-value pairs sorted by the keys. It combines the features of a list and a dictionary, keeping items in order automatically based on the key values.
⚙️

How It Works

Imagine you have a list of items, but you want them always sorted by a special label, like names in alphabetical order. SortedList in C# does exactly that for key-value pairs. When you add a new pair, it finds the right place to keep the list sorted by the key.

It works like a smart organizer that keeps your data neat without you having to sort it manually every time. Behind the scenes, it uses arrays to store keys and values, and it keeps them in sync so you can quickly find, add, or remove items by their keys.

💻

Example

This example shows how to create a SortedList, add some items, and print them in sorted order by key.

csharp
using System;
using System.Collections;

class Program
{
    static void Main()
    {
        SortedList fruits = new SortedList();
        fruits.Add("b", "Banana");
        fruits.Add("a", "Apple");
        fruits.Add("c", "Cherry");

        foreach (DictionaryEntry item in fruits)
        {
            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
        }
    }
}
Output
Key: a, Value: Apple Key: b, Value: Banana Key: c, Value: Cherry
🎯

When to Use

Use SortedList when you need to store pairs of data and want them automatically sorted by the key. It is useful when order matters, like showing a phone book sorted by names or keeping a leaderboard sorted by scores.

It is best when you have a moderate number of items and want fast lookups by key with the added benefit of sorted order. For very large data or frequent insertions, other collections like SortedDictionary might be more efficient.

Key Points

  • SortedList stores key-value pairs sorted by keys.
  • It allows fast access by key and keeps data ordered.
  • Keys must be unique and comparable.
  • Good for moderate-sized collections where order matters.
  • Combines features of arrays and dictionaries.

Key Takeaways

SortedList keeps key-value pairs sorted automatically by key.
It provides fast lookups and ordered data storage.
Use it when you want sorted keys and quick access together.
Keys must be unique and support comparison.
For large or frequently changing data, consider SortedDictionary.