The SortedList<TKey, TValue>
in C# is a collection that stores key-value pairs in a sorted order based on the keys. It belongs to the System.Collections.Generic
namespace and is especially useful when you need quick, ordered access to elements. Unlike a standard Dictionary<TKey, TValue>
, the SortedList maintains elements in sorted order, allowing faster access to elements when order matters. In this tutorial, we'll explore the SortedList<TKey, TValue>
class, how to work with it, and practical examples of its use.
SortedList<TKey, TValue>
The SortedList<TKey, TValue>
is a collection of key-value pairs that automatically sorts the elements based on the keys in ascending order. The keys in a SortedList must implement IComparable
to facilitate this sorting. The SortedList is efficient for retrieval and sorting purposes but has slower insertions compared to Dictionary<TKey, TValue>
because elements need to be repositioned to maintain order.
O(log n)
access time for keys and faster sorting since it’s maintained at insertion.Creating a SortedList is straightforward. You need to specify the types for both TKey
and TValue
to enforce type safety.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Initialize an empty SortedList
SortedList<int, string> students = new SortedList<int, string>();
// Initialize a SortedList with elements
SortedList<string, decimal> priceCatalog = new SortedList<string, decimal>
{
{ "Laptop", 1200.50m },
{ "Smartphone", 799.99m },
{ "Headphones", 199.99m }
};
}
}
In this example, we create a SortedList<int, string>
called students
and a SortedList<string, decimal>
called priceCatalog
.
To add elements, use the Add
method or initializer syntax.
SortedList<int, string> students = new SortedList<int, string>();
students.Add(101, "Alice");
students.Add(102, "Bob");
students.Add(103, "Charlie");
// Alternative: Using initializer syntax
SortedList<string, decimal> priceCatalog = new SortedList<string, decimal>
{
{ "Laptop", 1200.50m },
{ "Smartphone", 799.99m }
};
You can access elements by their keys using the indexer, which returns the associated value.
string studentName = students[101]; // Returns "Alice"
decimal laptopPrice = priceCatalog["Laptop"]; // Returns 1200.50
To modify an element, simply assign a new value to an existing key.
students[101] = "Alicia"; // Modifies "Alice" to "Alicia"
priceCatalog["Laptop"] = 1100.00m; // Updates the price of "Laptop"
Elements can be removed using the Remove
or RemoveAt
methods:
Remove
: Removes the entry with the specified key.RemoveAt
: Removes an entry at a specified index.students.Remove(103); // Removes "Charlie" from the list
priceCatalog.RemoveAt(0); // Removes the first entry in the list, "Laptop"
Suppose you are managing an e-commerce price catalog where products need to be sorted by name to allow for easy alphabetical searching. A SortedList<string, decimal>
can help keep prices in order while making access efficient.
using System;
using System.Collections.Generic;
public class ProductCatalog
{
private SortedList<string, decimal> priceCatalog = new SortedList<string, decimal>();
public void AddProduct(string productName, decimal price)
{
if (!priceCatalog.ContainsKey(productName))
{
priceCatalog.Add(productName, price);
Console.WriteLine($"Added: {productName} - ${price}");
}
else
{
Console.WriteLine($"{productName} already exists in the catalog.");
}
}
public void UpdatePrice(string productName, decimal newPrice)
{
if (priceCatalog.ContainsKey(productName))
{
priceCatalog[productName] = newPrice;
Console.WriteLine($"Updated: {productName} - ${newPrice}");
}
else
{
Console.WriteLine($"{productName} not found in the catalog.");
}
}
public void RemoveProduct(string productName)
{
if (priceCatalog.Remove(productName))
{
Console.WriteLine($"Removed: {productName}");
}
else
{
Console.WriteLine($"{productName} not found in the catalog.");
}
}
public void DisplayCatalog()
{
Console.WriteLine("Product Catalog:");
foreach (var item in priceCatalog)
{
Console.WriteLine($"{item.Key}: ${item.Value}");
}
}
}
public class Program
{
public static void Main()
{
ProductCatalog catalog = new ProductCatalog();
// Add products
catalog.AddProduct("Laptop", 1200.50m);
catalog.AddProduct("Smartphone", 799.99m);
catalog.AddProduct("Headphones", 199.99m);
// Display catalog
catalog.DisplayCatalog();
// Update a product price and display catalog again
catalog.UpdatePrice("Laptop", 1150.75m);
catalog.DisplayCatalog();
// Remove a product and display catalog again
catalog.RemoveProduct("Headphones");
catalog.DisplayCatalog();
}
}
ProductCatalog
class maintains a SortedList<string, decimal>
to store product names and their prices in alphabetical order.AddProduct
method adds new products to the catalog if they do not already exist.UpdatePrice
method updates the price of an existing product.RemoveProduct
method removes a product by its name.DisplayCatalog
method shows all products in sorted order, which is handled automatically by SortedList
.This example demonstrates the use of SortedList
to manage product prices efficiently, enabling easy access and updates to products based on their names.
The SortedList<TKey, TValue>
class in C# is a powerful data structure that combines the benefits of key-value pair storage with automatic sorting. This makes it an excellent choice for various applications that require fast access and ordered data. By understanding its features, advantages, and practical applications, developers can leverage SortedList<TKey, TValue>
to create efficient, organized data management systems in their software projects. Whether you are managing student grades, inventory, or configuration settings, SortedList<TKey, TValue>
provides a reliable solution for maintaining order while ensuring quick retrieval of data.