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:
// 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" ));
}
} |
Output:
False
Example 2:
// 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 ));
}
} |
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: