C# | Check whether a SortedList object contains a specific key

SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key.

Syntax:

public virtual bool Contains (object key);

Here, key is the Key which is to be located in the SortedList object.

Return Value: This method returns the true if the SortedList object contains an element with the specified key otherwise, it returns false

Exceptions:

  • ArgumentNullException: If the key is null.
  • InvalidOperationException: If the comparer throws an exception.

Below programs illustrate the use of above-discussed method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to Check whether a SortedList
// object contains a specific key
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("1", "C++");
        mylist.Add("2", "Java");
        mylist.Add("3", "DSA");
        mylist.Add("4", "Python");
        mylist.Add("5", "C#");
  
        // Checking whether 4 is present
        // in SortedList or not
        Console.Write(mylist.Contains("4"));
    }
}

chevron_right


Output:

True

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to Check whether a SortedList
// object contains a specific key
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("First", "Ram");
        mylist.Add("Second", "Shyam");
        mylist.Add("Third", "Mohit");
        mylist.Add("Fourth", "Rohit");
        mylist.Add("Fifth", "Manish");
  
        // Checking whether 10 is present
        // in SortedList object or not
        Console.Write(mylist.Contains("Sixth"));
    }
}

chevron_right


Output:

False

Note:

  • Contains implements IDictionary.Contains. It behaves exactly as ContainsKey.
  • This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count.

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.