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:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
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" );
Console.WriteLine(myDict.Contains( "Brazil" ));
}
}
|
Output:
False
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
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" );
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:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...