Open In App

SortedList ContainsKey() Method in C# With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

Given a SortedList object, now our task is to check whether the given SortedList object contains the specific key or not. So to do this task we use  ContainsKey() method. This method is used to determine whether a SortedList object contains a specific key or not. It will return true if the key is found, otherwise, it will return false.

Syntax:

bool SortedList.ContainsKey(object key);

Where key is located in the SortedList object.

Example:

Input  : [(1, "Python"), (2, "c")]
Key    : 1
Output : Found
Input  : [(1, "Python"), (2, "c")]
Key    : 4
Output : Not Found

Approach:

  1. Create a sorted list.
  2. Add key and values to the sorted list.
  3. Check whether the particular key exists in the list using ContainsKey() method.
  4. Display the output.

C#




// C# program to check whether a SortedList 
// object contains a specific key or not
using System;
using System.Collections;
  
class GFG{
      
static public void Main()
{
      
    // Create sorted list
    SortedList data = new SortedList();
      
    // Add elements to data sorted list 
    data.Add(1, "Python");
    data.Add(2, "c");
    data.Add(3, "java");
    data.Add(4, "php");
    data.Add(5, "html");
    data.Add(6, "bigdata");
    data.Add(7, "java script");
      
    // Check whether the key - 1 is present
    // in the list or not
    if (data.ContainsKey(1))
        Console.WriteLine("Present in the List");
    else
        Console.WriteLine("Not in the List");
          
    // Check whether the key - 4 is present
    // in the list or not
    if (data.ContainsKey(4))
        Console.WriteLine("Present in the List");
    else
        Console.WriteLine("Not in the List");
      
    // Check whether the key - 8 is present
    // in the list or not
    if (data.ContainsKey(8))
        Console.WriteLine("Present in the List");
    else
        Console.WriteLine("Not in the List");
}
}


Output:

Present in the List
Present in the List
Not in the List


Last Updated : 16 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads