📌  相关文章
📜  C#|检查OrderedDictionary集合是否包含特定键(1)

📅  最后修改于: 2023-12-03 15:00:16.103000             🧑  作者: Mango

Check if an OrderedDictionary Collection Contains a Specific Key in C#

An OrderedDictionary is a collection that stores key-value pairs in the form of dictionary entries. The keys in an OrderedDictionary are sorted and maintained in their original order.

To check if an OrderedDictionary collection contains a specific key in C#, you can use the Contains method provided by the OrderedDictionary class.

Syntax
public bool Contains(object key);

The Contains method takes an object parameter representing the key to be searched in the OrderedDictionary collection. It returns a boolean value indicating whether the specified key is present in the collection or not.

Example
OrderedDictionary od = new OrderedDictionary();

od.Add("Bob", "Teacher");
od.Add("Alice", "Doctor");

if (od.Contains("Bob"))
{
    Console.WriteLine("Bob is present in the OrderedDictionary collection.");
}
else
{
    Console.WriteLine("Bob is not present in the OrderedDictionary collection.");
}

Output:

Bob is present in the OrderedDictionary collection.

In the above example, we create an OrderedDictionary collection od and add two key-value pairs to it. We then use the Contains method to check if the key "Bob" is present in the collection. Since "Bob" is indeed present, the program outputs "Bob is present in the OrderedDictionary collection."

Conclusion

The Contains method provided by the OrderedDictionary class is an efficient way to check if a specific key is present in an OrderedDictionary collection. By using this method, you can avoid iterating over the collection and looking for the key yourself, which can be time-consuming and error-prone.