C# | Number of elements in HashSet
Last Updated :
12 Jul, 2023
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:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet = new HashSet< int >();
for ( int i = 0; i < 5; i++) {
mySet.Add(i * 2);
}
Console.WriteLine(mySet.Count);
}
}
|
Example 2:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet = new HashSet< int >();
Console.WriteLine(mySet.Count);
}
}
|
Using the AsEnumerable and Count methods
- AsEnumerable: The AsEnumerable method is used to convert a collection into an enumerable type, enabling the use of LINQ extension methods.
- Count: The Count method returns the number of elements in a collection, providing a convenient way to determine its size.
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
static public void Main()
{
HashSet< int > numbers = new HashSet< int >();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
int elementCount = numbers.AsEnumerable().Count();
Console.WriteLine( "Number of elements in the HashSet: " + elementCount);
}
}
|
Output
Number of elements in the HashSet: 3
In this code, we create a HashSet called numbers and add three integer values to it. Then, we use the AsEnumerable() method to convert the HashSet to an IEnumerable<int>, and the Count() method from the Enumerable class to get the count of elements in the HashSet. The main heading is printed, followed by the elements of the HashSet and the count of elements.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...