C# SortedList.ContainsKey(): Efficient Key Existence Check

Learn how to efficiently check for the existence of a key within a C# `SortedList` using the `ContainsKey()` method. This tutorial explains the method's syntax, usage, and return values with clear examples. Improve your C# code by using this essential method for key-value pair management in `SortedList` collections.



Using the C# `SortedList.ContainsKey()` Method

Understanding `SortedList.ContainsKey()`

In C#, the `SortedList` class stores key-value pairs, automatically keeping the elements sorted by key. The `ContainsKey()` method efficiently checks if a specific key exists within the `SortedList`. This is a very efficient method for determining whether a key exists in a `SortedList`.

`SortedList` Characteristics

  • Sorted by Key: Elements are sorted based on their keys.
  • Internal Storage: Uses two arrays (one for keys, one for values).
  • Key Uniqueness: Duplicate keys are not allowed.
  • Dynamic Sizing: Automatically increases capacity as needed.
  • Customizable Sorting: You can specify a custom comparer for sorting (beyond the default `IComparable` implementation).
  • Index-Based Access: You can access elements by index, but the index might change if you add or remove elements.

`ContainsKey()` Syntax and Return Value

The `ContainsKey()` method's syntax is:

public virtual bool ContainsKey(object key);

It takes the key you want to check for as an argument. It returns `true` if the key exists; otherwise it returns `false`.

Example: Using `ContainsKey()`

This example demonstrates creating a `SortedList`, adding items, and then using `ContainsKey()` to check for specific keys. The example demonstrates how to create a `SortedList`, add key-value pairs, and then check if specific keys are present using the `ContainsKey()` method.

C# Code

using System;
using System.Collections;

public class SortedListExample {
    public static void Main(string[] args) {
        SortedList mySortedList = new SortedList();
        mySortedList.Add(10, "Ten");
        mySortedList.Add(20, "Twenty");
        // ... rest of the code ...
    }

    // ... helper function ...
}

When to Use `SortedList`

While `SortedList` is useful for managing sorted key-value pairs, it's important to note that its automatic sorting can impact performance, especially for large collections. For very large datasets or those where sorting isn't frequently needed, consider using a regular dictionary or list instead.

Conclusion

The `SortedList.ContainsKey()` method provides an efficient way to check for the existence of a key in a sorted list. Understanding its use, along with the characteristics of `SortedList`, helps you choose the appropriate data structure for your C# applications.