C# SortedList
In C#, a SortedList is a collection of key-value pairs that are sorted by the keys. SortedLists are useful for storing and retrieving items in a specific order based on their keys. In this tutorial, we'll discuss how to use a SortedList in C#.
Syntax
The syntax for creating a SortedList in C# is as follows:
SortedList mySortedList = new SortedList();
You can also create a SortedList with a specific initial capacity:
SortedList mySortedList = new SortedList(10);
To add items to the SortedList, use the Add() method:
mySortedList.Add(key, value);
To retrieve an item from the SortedList, use the indexer:
mySortedList[key];
To remove an item from the SortedList, use the Remove() method:
mySortedList.Remove(key);
Example
Let's say we want to create a SortedList called "myList" that stores the names and ages of a group of people. Here's how we can implement it:
SortedList myList = new SortedList();
myList.Add("Alex", 25);
myList.Add("Bob", 30);
myList.Add("Charlie", 20);
Console.WriteLine(myList["Bob"]); // Output: 30
myList.Remove("Charlie");
foreach (string name in myList.Keys) {
Console.WriteLine("{0} : {1}", name, myList[name]);
}
Output
When we run the example code above, the output will be:
30
Alex : 25
Bob : 30
This is because we added three items to the SortedList, retrieved the age of "Bob" using the indexer, removed "Charlie" from the SortedList, and then printed the remaining items using a foreach loop.
Explanation
In the example above, we created a SortedList called "myList" that stores the names and ages of a group of people. We added three items to the SortedList using the Add() method, retrieved the age of "Bob" using the indexer, removed "Charlie" from the SortedList using the Remove() method, and then printed the remaining items using a foreach loop.
Use
SortedList is useful when you need to store items in a specific order based on their keys, and when you need to retrieve items quickly based on their keys. It's also useful when you need to iterate over the items in the SortedList in a specific order.
Important Points
- SortedLists are slower than Dictionary and Hashtable when adding and removing items, but faster when iterating over items in sorted order.
- SortedLists can have duplicate keys, but not duplicate values.
- SortedLists are not thread-safe and may require synchronization in multi-threaded applications.
Summary
In this tutorial, we discussed how to use a SortedList in C#. We covered the syntax, example, output, explanation, use, and important points of SortedList in C#. With this knowledge, you can now use SortedList in your C# code to store items in a specific order based on their keys and retrieve items quickly based on their keys.