SortedList in C# combines features of arrays and hashtables, storing key-value pairs in sorted order by keys. Here's what you need to know:
- Maintains elements in sorted order automatically
- Allows lookups by key and index
- Useful for scenarios needing constant sorting and fast access
- Balances features of List and Dictionary
Key features:
- Unique, non-null keys
- Null or duplicate values allowed
- Automatic sorting on insertion
- Key and index-based access
Quick comparison:
Feature | SortedList | List | Dictionary |
---|---|---|---|
Sorting | Automatic | Manual | No sorting |
Key-based access | Yes | No | Yes |
Index-based access | Yes | Yes | No |
Performance (insertion) | O(n) | O(1) | O(1) |
Performance (retrieval) | O(log n) | O(1) by index | O(1) |
Related video from YouTube
SortedList basics
SortedList stores key-value pairs sorted by keys using two internal arrays:
- Keys array
- Corresponding values array
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
// Keys are now sorted: 1, 2, 3
Key points:
- Unique, non-null keys
- Null or duplicate values allowed
- Automatic sorting on insertion
- Key and index-based access
SortedList shines when you need:
- Quick lookups by key and index
- Constantly sorted collection
- Memory efficiency (vs SortedDictionary)
// Simple inventory system example
SortedList<string, int> inventory = new SortedList<string, int>();
inventory.Add("Apple", 50);
inventory.Add("Banana", 30);
inventory.Add("Orange", 40);
Console.WriteLine($"Apples in stock: {inventory["Apple"]}");
Console.WriteLine($"Second item: {inventory.Keys[1]} - {inventory.Values[1]}");
Making a SortedList
Create a SortedList:
using System.Collections.Generic;
// Generic SortedList
SortedList<TKey, TValue> myGenericList = new SortedList<TKey, TValue>();
// With initial values
SortedList<int, string> numberNames = new SortedList<int, string>()
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
Remember:
- Keys must be unique and non-null
- Values can be null or duplicate
- Automatic sorting by key
- Set initial capacity:
new SortedList<TKey, TValue>(capacity)
Adding items to SortedList
Use the Add()
method:
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
For duplicate keys, use the key indexer:
planets[3] = "Earth - Updated"; // Updates existing value
planets[4] = "Mars"; // Adds new key-value pair
sbb-itb-29cd4f6
Getting items from SortedList
Retrieve items:
Console.WriteLine(numberNames[1]); // Output: One
// Safe retrieval
if (numberNames.TryGetValue(2, out string result))
{
Console.WriteLine($"Key: 2, Value: {result}");
}
// Iteration
foreach (KeyValuePair<int, string> pair in numberNames)
{
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}
Removing items from SortedList
Remove items:
numberNames.Remove(1); // Removes by key
numberNames.RemoveAt(0); // Removes by index
numberNames.Clear(); // Removes all items
SortedList features
Key features:
Console.WriteLine($"Count: {numberNames.Count}");
Console.WriteLine($"Capacity: {numberNames.Capacity}");
if (numberNames.ContainsKey(2))
{
Console.WriteLine("Key 2 exists");
}
Wrap-up
SortedList offers:
- Automatic sorting
- Fast lookups
- Memory efficiency
- Custom sorting options
Consider SortedList when you need sorted data with quick access, but be mindful of its performance characteristics for large datasets or frequent modifications.