Hashtable containsKey

In this chapter you will learn:

  1. How to check if a key is contained in Hashtable

ContainsKey

We can use the ContainsKey() method to check if Hashtable contains a key.

using System;//from j a v a 2 s  . c  om
using System.Collections;

class MainClass
{

  public static void Main()
  {
    Hashtable myHashtable = new Hashtable();

    myHashtable.Add("AL", "Alabama");
    myHashtable.Add("CA", "California");
    myHashtable.Add("FL", "Florida");
    myHashtable.Add("NY", "New York");
    myHashtable.Add("WY", "Wyoming");

    foreach (string myKey in myHashtable.Keys)
    {
      Console.WriteLine("myKey = " + myKey);
    }
    foreach(string myValue in myHashtable.Values)
    {
      Console.WriteLine("myValue = " + myValue);
    }
    
    if (myHashtable.ContainsKey("FL"))
    {
      Console.WriteLine("myHashtable contains the key FL");
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to remove key and value pair from Hashtable
Home » C# Tutorial » Collections
HashSet
Set operation: Except
Set operator intersect
Remove with condition
HashSet contains
HashSet creation
HashSet removing element
Sub set operations
Hashtable
Hashtable ContainsValue
Add elements to a Hashtable
Hashtable containsKey
Remove from Hashtable
Hashtable to array
Queue
Generic Queue
Stack