Home C# Tutorial on SortedList in C#

Tutorial on SortedList in C#

The SortedList<K, V> class in C# is part of the System.Collections.Generic namespace and stores key-value pairs in sorted order based on the keys.

Similar to SortedDictionary<K, V>, it automatically maintains the order of keys, but SortedList<K, V> is more memory-efficient as it uses a sorted array internally.

This makes SortedList<K, V> ideal for situations where data is read more often than modified.

In this tutorial, we’ll cover:

1. Creating a SortedList<K, V>

To create a SortedList<K, V>, include the System.Collections.Generic namespace. K is the type of the key, and V is the type of the value.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        // Create an empty sorted list of string keys and int values
        SortedList<string, int> ages = new SortedList<string, int>();

        // Create a sorted list with initial values
        SortedList<string, string> capitals = new SortedList<string, string> {
            { "USA", "Washington, D.C." },
            { "France", "Paris" },
            { "Japan", "Tokyo" }
        };

        Console.WriteLine("Initial capitals sorted list:");
        foreach (var item in capitals) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Initial capitals sorted list:
France: Paris
Japan: Tokyo
USA: Washington, D.C.

In this example:

  • SortedList<string, int> ages = new SortedList<string, int>(); creates an empty sorted list.
  • SortedList<string, string> capitals initializes a sorted list with key-value pairs. The output shows the keys are automatically sorted in alphabetical order.

2. Adding Elements to the Sorted List

You can add elements to a sorted list using the Add method or by using the indexer [].

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> ages = new SortedList<string, int>();

        // Adding elements with Add
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);

        // Adding elements with indexer
        ages["Charlie"] = 35;

        Console.WriteLine("Ages sorted list:");
        foreach (var item in ages) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Ages sorted list:
Alice: 30
Bob: 25
Charlie: 35

In this example:

  • Add(“Alice”, 30) adds a key-value pair using Add.
  • ages[“Charlie”] = 35; adds or updates a key-value pair using the indexer.

Note: Adding a duplicate key with Add will throw an ArgumentException.

3. Accessing and Modifying Elements

You can access and modify elements in a sorted list using the key as an index.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> ages = new SortedList<string, int> {
            { "Alice", 30 },
            { "Bob", 25 }
        };

        // Access elements
        Console.WriteLine("Alice's age: " + ages["Alice"]);

        // Modify an existing element
        ages["Alice"] = 31;

        Console.WriteLine("Updated Alice's age: " + ages["Alice"]);
    }
}

Output:

Alice's age: 30
Updated Alice's age: 31

In this example:

  • ages[“Alice”] accesses Alice’s age.
  • ages[“Alice”] = 31; updates Alice’s age to 31.

Note: Attempting to access a non-existent key with [] will throw a KeyNotFoundException. Use TryGetValue to avoid this.

Using TryGetValue to Access Elements Safely

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> ages = new SortedList<string, int> { { "Alice", 30 } };

        if (ages.TryGetValue("Bob", out int age)) {
            Console.WriteLine("Bob's age: " + age);
        } else {
            Console.WriteLine("Bob is not in the sorted list.");
        }
    }
}

Output:

Bob is not in the sorted list.

4. Removing Elements

You can remove elements from a sorted list using Remove or Clear.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> ages = new SortedList<string, int> {
            { "Alice", 30 },
            { "Bob", 25 },
            { "Charlie", 35 }
        };

        // Remove a specific element by key
        ages.Remove("Bob");

        // Clear all elements from the sorted list
        ages.Clear();

        Console.WriteLine("Ages sorted list count after clearing: " + ages.Count);
    }
}

Output:

Ages sorted list count after clearing: 0

In this example:

  • Remove(“Bob”) removes the entry with the key “Bob”.
  • Clear() removes all entries from the sorted list.

5. Checking for Keys and Values

You can check if a sorted list contains a specific key or value using ContainsKey and ContainsValue.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> ages = new SortedList<string, int> {
            { "Alice", 30 },
            { "Bob", 25 }
        };

        // Check if a key exists
        Console.WriteLine("Contains key 'Alice': " + ages.ContainsKey("Alice"));

        // Check if a value exists
        Console.WriteLine("Contains value 25: " + ages.ContainsValue(25));
    }
}

Output:

Contains key 'Alice': True
Contains value 25: True

In this example:

  • ContainsKey(“Alice”) checks if the key “Alice” exists.
  • ContainsValue(25) checks if the value 25 exists.

6. Iterating Through a Sorted List

You can iterate through a sorted list using a foreach loop to access both keys and values. The items are iterated in sorted order of the keys.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, string> capitals = new SortedList<string, string> {
            { "USA", "Washington, D.C." },
            { "France", "Paris" },
            { "Japan", "Tokyo" }
        };

        Console.WriteLine("Country capitals:");
        foreach (KeyValuePair<string, string> item in capitals) {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}

Output:

Country capitals:
France: Paris
Japan: Tokyo
USA: Washington, D.C.

In this example:

  • The foreach loop iterates over each KeyValuePair<string, string>, and the items are displayed in sorted order of the keys.

7. Practical Examples of SortedList<K, V> in Real Scenarios

Example 1: Storing Product Prices in Alphabetical Order

You can use a sorted list to store product prices sorted by product names.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, decimal> products = new SortedList<string, decimal> {
            { "Apples", 1.20m },
            { "Bananas", 0.75m },
            { "Cherries", 2.50m }
        };

        Console.WriteLine("Product prices:");
        foreach (var item in products) {
            Console.WriteLine($"{item.Key}: ${item.Value}");
        }
    }
}

Output:

Product prices:
Apples: $1.20
Bananas: $0.75
Cherries: $2.50

In this example:

  • The sorted list maintains the alphabetical order of product names.

Example 2: Ranking Players by Scores in Ascending Order

A SortedList<K, V> can store player scores sorted by player names in ascending order.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        SortedList<string, int> playerScores = new SortedList<string, int> {
            { "Alice", 120 },
            { "Bob", 150 },
            { "Charlie", 130 }
        };

        Console.WriteLine("Player Scores:");
        foreach (var item in playerScores) {
            Console.WriteLine($"{item.Key}: {item.Value} points");
        }
    }
}

Output:

Player Scores:
Alice: 120 points
Bob: 150 points
Charlie: 130 points

In this example:

  • The sorted list maintains players’ scores in alphabetical order by player name.

Summary

In this tutorial, we covered the SortedList<K, V> class in C# and demonstrated its features:

  1. Creating a SortedList<K, V>: Initializing sorted lists with or without initial values.
  2. Adding Elements: Using Add and indexer [] to add items.
  3. Accessing and Modifying Elements: Using keys to access and modify values, and TryGetValue for safe access.
  4. Removing Elements: Using Remove and Clear.
  5. Checking for Keys and Values: Using ContainsKey and ContainsValue.
  6. Iterating Through a Sorted List: Using foreach to access both keys and values in sorted order.
  7. Practical Examples: Storing product prices and player scores in sorted order.

The SortedList<K, V> class is an efficient and memory-friendly collection type for managing sorted key-value pairs, making it ideal for applications requiring sorted lookups and fast retrieval, such as storing alphabetized lists, ranking systems, and more.

 

You may also like