Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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"));
    }
}


Output:

True

Example 2:




// 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"));
    }
}


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:



Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads