![]() |
VOOZH | about |
In C# both, SortedList and SortedDictionary store key-value pairs in a sorted order. Understanding the main difference between SortedList and SortedDictionary plays a very important role in choosing the right collection for our use case. The main difference between SortedList and SortedDictionary is:
Features | SortedList | SortedDictionary |
|---|---|---|
| SortedList uses an array internally. | SortedDictionary uses a self-balancing tree (like a red-black tree) internally. |
Indexed Access | SortedList supports indexed access. | SortedDictionary does not support indexed access. |
Key-value Access | Access by index and key | Access only by key |
Use Cases | SortedList is suitable for small, static collections. | SortedDictionary is suitable for large, dynamic collections. |
Memory Efficiency | SortedList requires less memory. | SortedDictionary requires more memory. |
Memory Fragmentation | In SortedList memory fragmentation can be higher because elements are in array. | In SortedDictionary memory fragmentationn is lower because memory is allocated dynamically. |
In C#, SortedList is a collection of key-value pairs, where the keys are automatically sorted in asscending order. It ensues that the key-value pairs remain sorted as we add, remove or modify items in the collection. SortedList is available in both generic and non generic types:
Example: This example demosntrates how to create a non-generic SortedList in C#.
Key: 1, Value: Java Key: 2, Value: C# Key: 3, Value: Js Key: 4, Value: C++
In C# SortedDictionary is a collection that stores key-value pairs in a sorted order based on the keys. SortedDictionary is a generic collection which means we can modify the types for both the keys and values. It is dynamic in nature, the size of the dictionary adjusts dynamically based on the number of elements added or removed. SortedDictionary is available in generic type:
SortedDictionary<TKey, TValue>: It is defined in the System.Collections.Generic namespace.
Example: This example demosntrates how to create a SortedDictionary in C#.
SortedDictionary: Rank 1: Java Rank 2: JavaScript Rank 3: C++ Rank 4: C Rank 5: Ruby