VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-search-in-a-sortedlist-object/

⇱ C# | Search in a SortedList object - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:
  • A SortedList element can be accessed by its key or by its index.
  • A SortedList object internally maintains two arrays to store the elements of the list, i.e, one array for the keys and another array for the associated values.
  • A key cannot be null, but a value can be.
  • The capacity of a SortedList object is the number of elements the SortedList can hold.
  • A SortedList does not allow duplicate keys.
  • Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting.
  • Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
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:
  • ArgumentNullException : If the key is null.
  • InvalidOperationException : If the comparer throws an exception.
Below given are some examples to understand the implementation in a better way: Example 1:
Output:
True
Example 2:
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:
Comment

Explore