A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/c-sharp/c-sharp-search-in-a-sortedlist-object/ below:

C# | Search in a SortedList object

C# | Search in a SortedList object

Last Updated : 11 Jul, 2025

SortedList class is a collection of

(key, value) pairs

which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under

System.Collections

namespace.

SortedList.ContainsKey(Object)

method is used to check whether a SortedList object contains a specific key or not.

Properties: Syntax:
public virtual bool ContainsKey (object key);

Here,

key

is the key to locate in the SortedList object.

Return Value:

This method will return

True

if the SortedList object contains an element with the specified key otherwise it returns

False

.

Exceptions:

Below given are some examples to understand the implementation in a better way:

Example 1: CSHARP
// C# code to check if a SortedList
// object contains a specific key
using System;
using System.Collections;

class GFG {

    // Driver code
    public static void Main()
    {

        // Creating an SortedList
        SortedList mySortedList = new SortedList();

        // Adding elements to SortedList
        mySortedList.Add("h", "Hello");
        mySortedList.Add("g", "Geeks");
        mySortedList.Add("f", "For");
        mySortedList.Add("n", "Noida");

        // Checking if a SortedList object
        // contains a specific key
        Console.WriteLine(mySortedList.ContainsKey("g"));
    }
}
Example 2: CSHARP
// C# code to check if a SortedList
// object contains a specific key
using System;
using System.Collections;

class GFG {

    // Driver code
    public static void Main()
    {

        // Creating an SortedList
        SortedList mySortedList = new SortedList();

        // Adding elements to SortedList
        mySortedList.Add("h", "Hello");
        mySortedList.Add("g", "Geeks");
        mySortedList.Add("f", "For");
        mySortedList.Add("n", "Noida");

        // Checking if a SortedList object
        // contains a specific key
        // It should throw ArgumentNullException
        // as the Key can not be null
        Console.WriteLine(mySortedList.ContainsKey(null));
    }
}
Error:
Unhandled Exception: System.ArgumentNullException: Key cannot be null. Parameter name: key
Note:

This method uses a binary search algorithm, therefore, this method is an O(log n) operation, where n is Count.

Reference:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4