C# | Number of elements in HashSet
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
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); } } |
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); } } |
0
Reference:
Recommended Posts:
- C# | Remove all elements from a HashSet
- C# | Remove all elements in a collection from a HashSet
- C# | Check if HashSet and the specified collection contain the same elements
- C# | Remove elements from a HashSet with conditions defined by the predicate
- C# | Check if a HashSet and a specified collection share common elements
- C# | HashSet Class
- C# | Add element to HashSet
- C# | Union of two HashSet
- HashSet in C# with Examples
- C# | Getting an enumerator that iterates through HashSet<T>
- C# | Remove the specified element from a HashSet
- C# | Check if a HashSet contains the specified element
- C# | Create HashSet from another collection
- C# | Check if two HashSet<T> objects are equal
- C# | Check if a HashSet is a superset of the specified collection
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.



