C# | Check if ListDictionary contains a specific key

ListDictionary.Contains(Object) method is used to check whether the ListDictionary contains a specific key or not.

Syntax:

public bool Contains (object key);

Here, key is the key to locate in the ListDictionary.



Return Value: The method returns true if the ListDictionary contains an entry with the specified key, otherwise it returns false.

Exception: This method will give ArgumentNullException if the key is null.

Below given are some examples to understand the implementation in a better way:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if ListDictionary
// contains a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a ListDictionary named myDict
        ListDictionary myDict = new ListDictionary();
  
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
        myDict.Add("Netherlands", "Amsterdam");
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // Checking if ListDictionary contains
        // the key "Brazil"
        Console.WriteLine(myDict.Contains("Brazil"));
    }
}

chevron_right


Output:

False

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to check if ListDictionary
// contains a specific key
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a ListDictionary named myDict
        ListDictionary myDict = new ListDictionary();
  
        myDict.Add("Australia", "Canberra");
        myDict.Add("Belgium", "Brussels");
        myDict.Add("Netherlands", "Amsterdam");
        myDict.Add("China", "Beijing");
        myDict.Add("Russia", "Moscow");
        myDict.Add("India", "New Delhi");
  
        // Checking if ListDictionary contains
        // the key "null". This should raise
        // "ArgumentNullException" as the key is null
        Console.WriteLine(myDict.Contains(null));
    }
}

chevron_right


Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Key cannot be null.
Parameter name: key

Note: This method is an O(n) operation, where n is Count.

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.