C# SortedList
In C#, SortedList is a collection that is automatically sorted by key. It stores data as key-value pairs and automatically sorts by key order (ascending) when adding or updating.
The SortedList class represents a collection of key/value pairs sorted by key.key => valueThese key/value pairs can be accessed by key and by index.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is a dynamic array (ArrayList); if you access items using a key, it is a hash table (Hashtable). The items in the collection are always sorted by key value.
SortedList has two versions:
- non-generic
SortedList(System.Collections.SortedList) - Generics
SortedList<TKey, TValue>(System.Collections.Generic.SortedList<TKey, TValue>)
Features:
- Automatic sorting: All keys are sorted in ascending order; there is no need to manually call a sorting method.
- Key-value pair storage: Each key is unique; the value associated with it can be repeated.
- Dynamically adjust capacity: Automatically adjusts the size of internal storage as needed.
- Index accessAccess data by key or index.
- Efficient operations: The average time complexity of retrieval, insertion, and deletion is O(log n).
Methods and properties of the SortedList class
The table below listsSortedListSome common uses of the classProperty:
| Attribute Name | Type | Description |
|---|---|---|
Count | int | Get the number of key-value pairs in the sorted list. |
Capacity | int | Get or set the capacity of the sorted list. |
Comparer | IComparerorIComparer<TKey> | Gets the comparer used to sort the keys. |
IsReadOnly | bool | Indicates whether the sorted list is read-only. |
IsFixedSize | bool | Indicates whether the sorted list has a fixed size (alwaysfalse)。 |
Keys | ICollectionorIList<TKey> | Get all keys in the sorted list. |
Values | ICollectionorIList<TValue> | Get all values in the sorted list. |
The table below listsSortedListSome common uses of the classMethods:
| Method Name | Return Type | Description |
|---|---|---|
| Adding and removing | ||
Add(TKey key, TValue value) | void | Adds the specified key/value pair to the sorted list. |
Remove(TKey key) | bool | Removes the element with the specified key from the sorted list. |
RemoveAt(int index) | void | Removes the key/value pair at the specified index in the sorted list. |
Clear() | void | Remove all elements from the sorted list. |
| Searching and accessing | ||
ContainsKey(TKey key) | bool | Determines whether the sorted list contains the specified key. |
ContainsValue(TValue value) | bool | Determines whether the sorted list contains the specified value. |
IndexOfKey(TKey key) | int | Returns the index of the specified key. |
IndexOfValue(TValue value) | int | Returns the index of the specified value. |
TryGetValue(TKey key, out TValue value) | bool | Gets the value associated with the specified key, and returns it if it exists.true。 |
| Copying and enumerating | ||
CopyTo(Array array, int index) | void | Copies the elements of the sorted list to an array, starting at the specified index. |
GetEnumerator() | IEnumerator | Returns an enumerator used to iterate through the elements in the sorted list. |
Example
The following example demonstrates the concept of SortedList.
Non-generic version operations:
Example
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl.Add("001", "Zara Ali");
sl.Add("002", "Abida Rehman");
sl.Add("003", "Joe Holzner");
sl.Add("004", "Mausam Benazir Nur");
sl.Add("005", "M. Amlan");
sl.Add("006", "M. Arif");
sl.Add("007", "Ritesh Saikia");
if (sl.ContainsValue("Nuha Ali"))
{
Console.WriteLine("This student name is already in the list");
}
else
{
sl.Add("008", "Nuha Ali");
}
// Get the collection of keys
ICollection key = sl.Keys;
foreach (string k in key)
{
Console.WriteLine(k + ": " + sl[k]);
}
}
}
}
When the above code is compiled and executed, it produces the following results:
001: Zara Ali 002: Abida Rehman 003: Joe Holzner 004: Mausam Banazir Nur 005: M. Amlan 006: M. Arif 007: Ritesh Saikia 008: Nuha Ali
Generic version:
Example
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a generic SortedList
SortedList<int, string> sortedList = new SortedList<int, string>();
// Add key-value pair
sortedList.Add(2, "Banana");
sortedList.Add(1, "Apple");
sortedList.Add(3, "Cherry");
// Automatically sort by key
Console.WriteLine("SortedList contents:");
foreach (var kvp in sortedList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
// Lookup and access
Console.WriteLine($"\nValue for key 2: {sortedList[2]}"); // Output: Banana
// Delete elements
sortedList.Remove(1);
Console.WriteLine("\nAfter removing key 1:");
foreach (var kvp in sortedList)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
// Check key and value
Console.WriteLine($"\nContains key 3: {sortedList.ContainsKey(3)}"); // output: True
Console.WriteLine($"Contains value 'Apple': {sortedList.ContainsValue("Apple")}"); // Output: False
}
}