Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C# | Number of elements in HashSet

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. You can use HashSet.Count Property to count the number of elements in a HashSet.

Syntax:

mySet.Count;

Here mySet is the HashSet

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

Example 1:




// C# code to get the number of
// elements that are contained in HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet = new HashSet<int>();
  
        // Inserting elements in HashSet
        for (int i = 0; i < 5; i++) {
            mySet.Add(i * 2);
        }
  
        // To get the number of
        // elements that are contained in HashSet
        Console.WriteLine(mySet.Count);
    }
}

Output:

5

Example 2:




// C# code to get the number of
// elements that are contained in HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet = new HashSet<int>();
  
        // To get the number of
        // elements that are contained in HashSet.
        // Note that, here the HashSet is empty
        Console.WriteLine(mySet.Count);
    }
}

Output:

0

Reference:


My Personal Notes arrow_drop_up
Last Updated : 01 Feb, 2019
Like Article
Save Article
Similar Reads