Check if SortedDictionary contains the specified key or not in C#

To check if a SortedDictionary contains a specified key, C# provides the ContainsKey() method. This method returns true if the key exists in the dictionary, otherwise false. The SortedDictionary maintains its elements in sorted order by key, making key lookups efficient with O(log n) time complexity.

Syntax

Following is the syntax for the ContainsKey() method −

public bool ContainsKey(TKey key)

Parameters

  • key − The key to locate in the SortedDictionary.

Return Value

Returns true if the SortedDictionary contains an element with the specified key; otherwise, false.

Using ContainsKey() with Integer Keys

Example

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
      sortedDict.Add(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");
      
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      
      Console.WriteLine("\nThe SortedDictionary has the key 200? = " + sortedDict.ContainsKey(200));
      Console.WriteLine("The SortedDictionary has the key 250? = " + sortedDict.ContainsKey(250));
   }
}

The output of the above code is −

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

The SortedDictionary has the key 200? = True
The SortedDictionary has the key 250? = False

Using ContainsKey() with String Keys

Example

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
      sortedDict.Add("A", "John");
      sortedDict.Add("B", "Andy");
      sortedDict.Add("C", "Tim");
      sortedDict.Add("D", "Ryan");
      sortedDict.Add("E", "Kevin");
      sortedDict.Add("F", "Katie");
      sortedDict.Add("G", "Brad");
      
      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
         Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
      
      Console.WriteLine("\nThe SortedDictionary has the key F? = " + sortedDict.ContainsKey("F"));
      Console.WriteLine("The SortedDictionary has the key Z? = " + sortedDict.ContainsKey("Z"));
   }
}

The output of the above code is −

SortedDictionary key-value pairs...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad

The SortedDictionary has the key F? = True
The SortedDictionary has the key Z? = False

Practical Example with Conditional Logic

Example

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedDictionary<string, int> inventory = new SortedDictionary<string, int>();
      inventory.Add("Apples", 50);
      inventory.Add("Bananas", 30);
      inventory.Add("Oranges", 25);
      inventory.Add("Grapes", 15);
      
      string[] itemsToCheck = {"Apples", "Mangoes", "Grapes", "Pineapples"};
      
      Console.WriteLine("Inventory Status:");
      foreach (string item in itemsToCheck) {
         if (inventory.ContainsKey(item)) {
            Console.WriteLine($"{item}: Available ({inventory[item]} units)");
         } else {
            Console.WriteLine($"{item}: Not available");
         }
      }
   }
}

The output of the above code is −

Inventory Status:
Apples: Available (50 units)
Mangoes: Not available
Grapes: Available (15 units)
Pineapples: Not available

Conclusion

The ContainsKey() method provides an efficient way to check for key existence in a SortedDictionary. It returns a boolean value and is commonly used in conditional logic to prevent exceptions when accessing dictionary elements or to validate data before processing.

Updated on: 2026-03-17T07:04:36+05:30

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements