C# | Check if OrderedDictionary collection contains a specific key
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:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
Console.WriteLine(myDict.Contains( "Key6" ));
}
}
|
Output:
False
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
if (myDict.Contains( "key4" ))
myDict.Remove( "key4" );
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.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary.contains?view=netframework-4.7.2
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...