📌  相关文章
📜  C#|检查哈希表是否包含特定的密钥

📅  最后修改于: 2021-05-29 18:19:00             🧑  作者: Mango

Hashtable类表示键和值对的集合,这些键和值对是根据键的哈希码进行组织的。该键用于访问集合中的项目。 Hashtable.ContainsKey(Object)方法用于检查Hashtable是否包含特定键。

句法:

public virtual bool ContainsKey(object key);

范围:

返回类型:如果Hashtable包含具有指定键的元素,则返回true,否则返回false 。此方法的返回类型为System.Boolean

异常:如果为null,则此方法可以提供ArgumentNullException。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to check if the HashTable
// contains a specific key
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("g", "geeks");
        myTable.Add("c", "c++");
        myTable.Add("d", "data structures");
        myTable.Add("q", "quiz");
  
        // check if the HashTable contains
        // the required key or not.
        if (myTable.ContainsKey("c"))
            Console.WriteLine("myTable contains the key");
        else
            Console.WriteLine("myTable doesn't contain the key");
    }
}
输出:
myTable contains the key

范例2:

// C# code to check if the HashTable
// contains a specific key
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable
        Hashtable myTable = new Hashtable();
  
        // Adding elements in Hashtable
        myTable.Add("India", "Country");
        myTable.Add("Chandigarh", "City");
        myTable.Add("Mars", "Planet");
        myTable.Add("China", "Country");
  
        // check if the HashTable contains
        // the required key or not.
        if (myTable.ContainsKey("Earth"))
            Console.WriteLine("myTable contains the key");
        else
            Console.WriteLine("myTable doesn't contain the key");
    }
}
输出:
myTable doesn't contain the key

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.containskey?view=netframework-4.7.2