C# | Count the number of key/value pairs in the Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable.

Syntax:

myTable.Count

Here, myTable is the name of the Hashtable.



Below given are some examples to understand the implementation in a better way:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get the number of key-and-value
// pairs contained in the Hashtable.
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("2", "Even & Prime");
        myTable.Add("3", "Odd & Prime");
        myTable.Add("4", "Even & non-prime");
        myTable.Add("9", "Odd & non-prime");
  
        // To get the number of key-and-value
        // pairs contained in the Hashtable.
        Console.WriteLine(myTable.Count);
    }
}

chevron_right


Output:

4

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to get the number of key-and-value
// pairs contained in the Hashtable.
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an empty Hashtable
        Hashtable myTable = new Hashtable();
  
        // To get the number of key-and-value
        // pairs contained in the Hashtable.
        Console.WriteLine(myTable.Count);
    }
}

chevron_right


Output:

0

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.