In C#, SortedList is a collection class provided by the .NET Framework that represents a collection of key/value pairs sorted by the keys and accessible by key and by index. It's a generic class, meaning you can define the types for both the keys and the values.
Here's a breakdown of the SortedList class in C#:
1. Sorting Mechanism: The SortedList maintains its elements in sorted order based on the keys. When adding or removing items, the list automatically reorders itself to maintain the sorted order according to the keys.
2. Key-Value Pairs: Each element in a SortedList is a key-value pair. The keys must be unique and must be of a comparable type (implementing IComparable or by using a custom comparer). The values can be of any type.
3. Indexed Access: You can access elements in a SortedList using an integer index or a corresponding key. The elements are accessible by their index using the standard indexing syntax, and they can also be accessed using the associated key.
4. Efficient Searching: SortedList uses a binary search algorithm internally to quickly locate items based on the keys. This provides efficient searching operations.
5. Performance: The SortedList class offers efficient performance for searching by key and for retrieving items by index, but it can be slower for insertion and removal operations compared to other collection types like Dictionary due to the need for maintaining the sorted order.
6. Usage: To use a SortedList, you need to import the System.Collections namespace and create an instance of the SortedList class with appropriate type parameters for keys and values.
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
// Create a SortedList with string keys and int values
SortedList<string, int> sortedList = new SortedList<string, int>();
// Adding items
sortedList.Add("Key1", 10);
sortedList.Add("Key2", 20);
sortedList.Add("Key3", 30);
// Accessing items by key
Console.WriteLine(sortedList["Key2"]); // Outputs: 20
// Accessing items by index
Console.WriteLine(sortedList.Values[0]); // Outputs: 10
// Iterating through the SortedList
foreach (var kvp in sortedList)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
In this example, we create a SortedList with string keys and int values, add items to it, and demonstrate accessing elements by both key and index.
No comments:
Post a Comment