C# SortedDictionary
In C#, a SortedDictionary is a collection of key/value pairs that are sorted by key. The keys in a SortedDictionary must be unique, and the values can be any type. In this tutorial, we'll discuss how to use SortedDictionary in C#.
Syntax
The syntax for creating a SortedDictionary in C# is as follows:
SortedDictionary<TKey, TValue> myDict = new SortedDictionary<TKey, TValue>();
Here, "TKey" represents the data type for the keys in the dictionary, and "TValue" represents the data type for the values.
Example
Let's say we want to create a SortedDictionary that represents the inventory of a store. We can use the product name as the key and the quantity as the value. Here's how we can implement it:
SortedDictionary<string, int> inventory = new SortedDictionary<string, int>();
inventory.Add("Apple", 10);
inventory.Add("Banana", 5);
inventory.Add("Orange", 20);
foreach (KeyValuePair<string, int> item in inventory) {
Console.WriteLine("Product: {0}, Quantity: {1}", item.Key, item.Value);
}
Output
When we run the example code above, the output will be:
Product: Apple, Quantity: 10
Product: Banana, Quantity: 5
Product: Orange, Quantity: 20
This is because the SortedDictionary was initialized with three key/value pairs, and the foreach loop was used to print out each key/value pair.
Explanation
In the example above, we created a SortedDictionary called "inventory" that represents the inventory of a store. We added three key/value pairs to the SortedDictionary using the Add method, and then used a foreach loop to iterate through each key/value pair and print it out to the console.
Use
SortedDictionary is useful when you want to store a collection of key/value pairs that are sorted by key. You can use SortedDictionary to store data that requires sorting by key, such as an inventory system or a record of customer orders.
Important Points
- The items in a SortedDictionary are sorted by key in ascending order by default, but you can provide a custom Comparer to specify a different ordering.
- The keys in a SortedDictionary must be unique, and the values can be any type.
- You can use methods such as Add, Remove, and Count to modify and access the items in a SortedDictionary.
Summary
In this tutorial, we discussed how to use SortedDictionary in C#. We covered the syntax, example, output, explanation, use, and important points of SortedDictionary in C#. With this knowledge, you can now use SortedDictionary in your C# code to store a collection of key/value pairs that are sorted by key.