Sortedlist Containskey() Method In C#

In this guide, we will explore the functionality of the "SortedList.ContainsKey" method in C#, covering its syntax, parameters, and usage examples.

What is the SortedList.ContainsKey method?

The SortedList.ContainsKey function is a feature found in C# programming. It belongs to the SortedList class, which manages a set of key/value pairs organized based on the keys. This class is located within the "System.Collection namespace".

The individual elements in the list are stored in a pair of arrays, with one array for the keys and another for the values, both controlled by a SortedList instance. Each element can be retrieved as a key/value pair object of type "DictionaryEntry". While a value within this structure can be null, the key must always have a non-null value.

The capacity of a SortedList object refers to the maximum number of elements it can hold. As new elements are inserted into a SortedList, reallocation occurs automatically to enhance its capacity. Reducing the capacity can be achieved by employing TrimToSize or adjusting the capacity property for individual reductions.

The SortedList class in C# organizes elements according to keys. The sorting process can be achieved through the built-in IComparable implementation or by supplying a custom IComparer when creating an instance. This feature allows for versatile sorting options, supporting both default key order and personalized sorting conditions, thereby improving versatility in handling data. It's important to note that a SortedList doesn't allow duplicate keys in either scenario.

Based on the sorting order, the index order is generated. When a new element is inserted, the index is recalibrated to reflect the new addition in the SortedList in the correct sorted manner. Similarly, when an element is deleted, the index is readjusted accordingly. Hence, the position of a particular key/value pair might vary due to additions or deletions within the SortedList container.

Syntax:

It has the following syntax:

Example

public virtual bool ContainsKey (object key);

Return Value:

Boolean: When a SortedList object contains an element with the specified key, it will return true; otherwise, it will return false.

Approach:

  • First, create a sorted list.
  • Next, add a key and values to the sorted list.
  • Use the ContainsKey method to see if the specified key is in the list.
  • Display the output.
  • Example:

    Example
    
    using System;
    using System.Collections;
    public class ExampleSortedList
    {
       public static void Main()
       {
          // Establishes and initializes a new SortedList named my_SortedList
          SortedList my_SortedList = new SortedList();
          my_SortedList.Add( 10, "Ten" );
          my_SortedList.Add( 20, "Twenty" );
          my_SortedList.Add( 50, "Fifty" );
          my_SortedList.Add( 30, "Thirty" );
          my_SortedList.Add( 40, "Fourty" );
          // The SortedList values are displayed.
          Console.WriteLine( "The SortedList contains the following values and they are :" );
          PrintingIndexAndKeysAndValues(my_SortedList);
          // Finds a certain key via searching.
          int my_Key = 20;
          Console.WriteLine( "The key \"{0}\" is {1}.", my_Key, my_SortedList.ContainsKey( my_Key ) ? "present in the SortedList" : "NOT in the SortedList" );
          my_Key = 70;
          Console.WriteLine( "The key \"{0}\" is {1}.", my_Key, my_SortedList.ContainsKey( my_Key ) ? "in the SortedList" : "NOT present in the SortedList" );
          // Finds a certain value via searching.
          string my_Value = "Fourty";
          Console.WriteLine( "The value \"{0}\" is {1}.", my_Value, my_SortedList.ContainsValue( my_Value ) ? "present in the SortedList" : "NOT in the SortedList" );
          my_Value = "Hundred";
          Console.WriteLine( "The value \"{0}\" is {1}.", my_Value, my_SortedList.ContainsValue( my_Value ) ? "present in the SortedList" : "NOT present in the SortedList" );
       }
       public static void PrintingIndexAndKeysAndValues( SortedList my_List )  {
          Console.WriteLine( "\tINDEX\tKEY\tVALUE" );
          for ( int q = 0; q < my_List.Count; q++ )  {
             Console.WriteLine( "\t[{0}]:\t{1}\t{2}", q, my_List.GetKey(q), my_List.GetByIndex(q) );
          }
          Console.WriteLine();
       }
    }
    

Output:

Output

The SortedList contains the following values, and they are :
INDEX	KEY	VALUE
	[0]:	10	Ten
	[1]:	20	Twenty
	[2]:	30	Thirty
	[3]:	40	Fourty
	[4]:	50	Fifty
The key "20" is present in the SortedList.
The key "70" is NOT present in the SortedList.
The value "Fourty" is present in the SortedList.
The value "Hundred" is NOT present in the SortedList.

When Sorted Lists are useful?

There are multiple scenarios where the SortedList class may not be appropriate, despite its potential as a valuable resource for efficiently managing associated data pairs.

A SortedList inherently maintains its sorted order. Consequently, the list will automatically rearrange itself upon adding or removing an element to guarantee the correct sequence of elements. With the growth in the number of elements in the list, the operation becomes more resource-intensive.

SortedList proves to be a valuable resource, however, it is best suited for managing compact data sets that demand continuous sorting. Opting for a dictionary, hash set, or standard list is a superior approach when handling extensive collections as opposed to sorting intermittently.

Conclusion:

In summary, an excellent and efficient method for organizing ordered information is by utilizing a SortedList. The capability to access and retrieve data using specific keys offers us versatility. Once we have gained proficiency in working with it, the SortedList object becomes valuable in various aspects of our daily coding practices.

Input Required

This code uses input(). Please provide values below: