Represents a collection of key/value pairs that are sorted by the keys and are accessible by index.
The SortedList
class in the System.Collections
namespace provides a data structure that stores elements as key/value pairs, similar to a dictionary or hash table. However, SortedList
maintains its elements in ascending order based on their keys. This sorting allows for efficient retrieval of elements by index and ensures that iterating through the collection yields elements in a predictable order.
SortedList
implements the IDictionary
interface, meaning each element has a unique key and a corresponding value. Keys and values can be of any type (object
). However, for comparisons to work correctly, the keys must implement the IComparable
interface.
SortedList
instance can initially store.SortedList
.ICollection
containing the keys in the SortedList
.ICollection
containing the values in the SortedList
.SortedList
.SortedList
.SortedList
.SortedList
contains the specified key.SortedList
contains the specified key.SortedList
contains the specified value.SortedList
.SortedList
.SortedList
.SortedList
.This class does not contain any events.
using System;
using System.Collections;
public class Example {
public static void Main(string[] args) {
SortedList sl = new SortedList();
sl.Add("Apple", 1);
sl.Add("Banana", 2);
sl.Add("Cherry", 3);
Console.WriteLine("Count: " + sl.Count);
Console.WriteLine("Keys:");
foreach (object key in sl.Keys) {
Console.WriteLine(" - " + key);
}
Console.WriteLine("Values:");
foreach (object value in sl.Values) {
Console.WriteLine(" - " + value);
}
Console.WriteLine("Value for 'Banana': " + sl["Banana"]);
Console.WriteLine("Key at index 1: " + sl.GetKey(1));
Console.WriteLine("Value at index 0: " + sl.GetByIndex(0));
}
}