OrderedDictionary.Contains(Object)方法用于检查OrderedDictionary集合是否包含特定键。
句法:
public bool Contains (object key);
在这里, key是要在OrderedDictionary集合中找到的键。
返回值:如果OrderedDictionary集合包含具有指定键的元素,则此方法返回True ,否则返回False 。
下面给出了一些示例,以更好地理解实现:
范例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"));
}
}
输出:
False
范例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);
}
}
输出:
key1 --> value1
key2 --> value2
key3 --> value3
key4 --> value4
key5 --> value5
key1 --> value1
key2 --> value2
key3 --> value3
key5 --> value5
注意:如果键不存在或键为空,则使用Item [Object]属性可以返回空值。使用Contains方法确定OrderedDictionary集合中是否存在特定的键。
参考:
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.ordereddictionary.contains?view=netframework-4.7.2