SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key.
Syntax:
CSharp
Output:
CSharp
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.
// 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"));
}
}
TrueExample 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:
FalseNote:
- 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.