How do you use a SortedList<T> to store items in a specific order in C#?
- Actually, SortedList<TKey, TValue> stores key-value pairs sorted by keys.
- To store items in a specific order, use the key to represent the sorting criteria.
- Keys must be unique and implement IComparable or provide a custom
IComparer.
Example:
SortedList<int, string> sortedList = new SortedList<int, string>();
sortedList.Add(10, "Ten");
sortedList.Add(5, "Five");
sortedList.Add(20, "Twenty");
Follow:
// Items automatically sorted by keys: 5, 10, 20
If you want to sort by custom criteria, implement an IComparer and pass it to the
SortedList constructor.
Follow: