Introduction
The SortedList<TKey, TValue>
class in C# represents a collection of key/value pairs that are sorted by the keys and are accessible by both key and index. It is part of the System.Collections.Generic
namespace and combines the functionality of a dictionary and a list. The SortedList<TKey, TValue>
class provides efficient lookups, insertions, and deletions while maintaining the sorted order of keys.
Key Features of SortedList<TKey, TValue>
- Sorted Order: Maintains elements in sorted order based on the keys.
- Key-Value Pairs: Stores data in key/value pairs.
- Indexed Access: Provides access to elements by both key and index.
- Type Safety: Enforces type safety, ensuring that keys and values are of specified types.
- Dynamic Size: Automatically resizes as elements are added or removed.
Creating a SortedList
Declaration and Initialization
You can declare and initialize a SortedList<TKey, TValue>
in several ways:
Example
using System;
using System.Collections.Generic;
namespace SortedListExample
{
class Program
{
static void Main(string[] args)
{
// Creating an empty sorted list
SortedList<int, string> employees = new SortedList<int, string>();
// Creating a sorted list with initial elements
SortedList<int, string> departments = new SortedList<int, string>
{
{ 3, "Engineering" },
{ 1, "Human Resources" },
{ 2, "Finance" }
};
// Adding elements to the sorted list
employees.Add(101, "John Doe");
employees.Add(103, "Sam Brown");
employees.Add(102, "Jane Smith");
// Displaying elements
Console.WriteLine("Employees:");
foreach (var kvp in employees)
{
Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
}
}
}
}
Output
Employees:
ID: 101, Name: John Doe
ID: 102, Name: Jane Smith
ID: 103, Name: Sam Brown
Common Operations on SortedList
Adding Elements
- Add: Adds a key/value pair to the sorted list.
employees.Add(104, "Alice Johnson");
Removing Elements
- Remove: Removes the key/value pair with the specified key from the sorted list. Returns
true
if the key was found and removed; otherwise,false
.
bool isRemoved = employees.Remove(102); // true
- RemoveAt: Removes the key/value pair at the specified index.
employees.RemoveAt(0);
- Clear: Removes all key/value pairs from the sorted list.
employees.Clear();
Accessing Elements
- Indexer: Accesses elements by their key.
string employeeName = employees[101];
- Keys: Gets a collection containing the keys in the sorted list.
IList<int> keys = employees.Keys;
- Values: Gets a collection containing the values in the sorted list.
IList<string> values = employees.Values;
- ContainsKey: Checks if the sorted list contains the specified key. Returns
true
if the key is found; otherwise,false
.
bool hasEmployee = employees.ContainsKey(101); // true
- ContainsValue: Checks if the sorted list contains the specified value. Returns
true
if the value is found; otherwise,false
.
bool hasName = employees.ContainsValue("John Doe"); // true
Iterating Through a SortedList
You can iterate through a sorted list using a foreach
loop.
Example
foreach (var kvp in employees)
{
Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}");
}
Checking the SortedList Size
- Count: Gets the number of key/value pairs in the sorted list.
int count = employees.Count;
Practical Example
Let’s create a practical example where we use a SortedList<TKey, TValue>
to manage a collection of product prices, allowing the user to add, remove, and display prices.
Example
using System;
using System.Collections.Generic;
namespace ProductPricesExample
{
class Program
{
static void Main(string[] args)
{
SortedList<int, decimal> productPrices = new SortedList<int, decimal>();
// Adding product prices
AddPrice(productPrices, 1, 9.99m);
AddPrice(productPrices, 3, 19.99m);
AddPrice(productPrices, 2, 14.99m);
// Displaying product prices
DisplayPrices(productPrices);
// Removing a product price
RemovePrice(productPrices, 2);
// Displaying the updated product prices
DisplayPrices(productPrices);
}
static void AddPrice(SortedList<int, decimal> prices, int productId, decimal price)
{
prices[productId] = price;
Console.WriteLine($"Added price for product {productId}: {price:C}");
}
static void RemovePrice(SortedList<int, decimal> prices, int productId)
{
if (prices.Remove(productId))
{
Console.WriteLine($"Removed price for product {productId}");
}
else
{
Console.WriteLine($"Product ID {productId} not found");
}
}
static void DisplayPrices(SortedList<int, decimal> prices)
{
Console.WriteLine("Product Prices:");
foreach (var kvp in prices)
{
Console.WriteLine($"Product ID: {kvp.Key}, Price: {kvp.Value:C}");
}
}
}
}
Output
Added price for product 1: $9.99
Added price for product 3: $19.99
Added price for product 2: $14.99
Product Prices:
Product ID: 1, Price: $9.99
Product ID: 2, Price: $14.99
Product ID: 3, Price: $19.99
Removed price for product 2
Product Prices:
Product ID: 1, Price: $9.99
Product ID: 3, Price: $19.99
Conclusion
The SortedList<TKey, TValue>
class in C# provides a powerful way to manage collections of key/value pairs that are maintained in sorted order. It combines the functionality of a dictionary and a list, allowing for efficient lookups, insertions, and deletions while keeping the elements sorted by their keys. Understanding how to use SortedList<TKey, TValue>
effectively can help you manage collections of ordered data in your applications.