OrderedDictionary.Contains(Object) method is used to check whether the OrderedDictionary collection contains a specific key or not.
Syntax:
public bool Contains (object key);
Here, key is the key to locate in the OrderedDictionary collection.
Return Value: This method returns True if the OrderedDictionary collection contains an element with the specified key, otherwise, False.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to check if OrderedDictionary // collection contains a specific key using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver method
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
// Checking if OrderedDictionary
// collection contains a specific key
Console.WriteLine(myDict.Contains( "Key6" ));
}
} |
Output:
False
Example 2:
// C# code to check if OrderedDictionary // collection contains a specific key using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver method
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
// Displaying the key/value pairs in myDict
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
// Checking if OrderedDictionary collection
// contains a specific key
if (myDict.Contains( "key4" ))
myDict.Remove( "key4" );
// Displaying the key/value pairs in myDict
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
}
} |
Output:
key1 --> value1 key2 --> value2 key3 --> value3 key4 --> value4 key5 --> value5 key1 --> value1 key2 --> value2 key3 --> value3 key5 --> value5
Note: Using the Item[Object] property can return a null value if the key does not exist or if the key is null. Use the Contains method to determine if a specific key exists in the OrderedDictionary collection.