;

C# SortedList<TKey, TValue>


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.

Introduction to 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.

Why Use SortedList?

  • Automatic Sorting: Keeps elements sorted by keys, which is useful for ordered data retrieval.
  • Efficient Access: Allows O(log n) access time for keys and faster sorting since it’s maintained at insertion.
  • Comparable to Dictionary: Similar key-value pair structure but with added sorting.

Creating and Initializing a SortedList

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.

Adding, Accessing, and Modifying Elements

Adding Elements

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 }
};

Accessing Elements

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

Modifying Elements

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"

Removing Elements

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"

Real-World Example: Price Catalog Management

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.

Example

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();
    }
}

Explanation

  1. The ProductCatalog class maintains a SortedList<string, decimal> to store product names and their prices in alphabetical order.
  2. The AddProduct method adds new products to the catalog if they do not already exist.
  3. The UpdatePrice method updates the price of an existing product.
  4. The RemoveProduct method removes a product by its name.
  5. The 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.

Key Takeaways

  • Sorted Collection: Automatically sorts elements based on keys, making it ideal for ordered data retrieval.
  • Type Safety: Provides a type-safe way to store key-value pairs.
  • Flexible Access: Allows O(log n) time complexity for accessing elements by keys.
  • Efficient for Sorted Data Needs: Best suited for scenarios where sorted order is required and insertion/removal operations are not very frequent.

Summary

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.