1
How to define HashSet<T> collection in C#, which collection is used to store unique values?
How to define HashSet<T> collection in C#, which collection is used to store unique values?
A HashSet<T> is an unordered collection of the unique elements. It comes under 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.
Characteristics of HashSet Class:
| Constructor | Description |
|---|---|
| HashSet() | Initializes a new instance of the HashSet class that is empty and uses the default equality comparer for the set type. |
| HashSet(IEnumerable) | Initializes a new instance of the HashSet class that uses the default equality comparer for the set type, contains elements copied from the specified collection, and has sufficient capacity to accommodate the number of elements copied. |
| HashSet(IEnumerable, IEqualityComparer) | Initializes a new instance of the HashSet class that uses the specified equality comparer for the set type, contains elements copied from the specified collection, and has sufficient capacity to accommodate the number of elements copied. |
| HashSet(IEqualityComparer) | Initializes a new instance of the HashSet class that is empty and uses the specified equality comparer for the set type. |
| HashSet(Int32) | Initializes a new instance of the HashSet class that is empty, but has reserved space for capacity items and uses the default equality comparer for the set type. |
| HashSet(Int32, IEqualityComparer) | Initializes a new instance of the HashSet class that uses the specified equality comparer for the set type, and has sufficient capacity to accommodate capacity elements. |
| HashSet(SerializationInfo, StreamingContext) | Initializes a new instance of the HashSet class with serialized data. |
Example:
// C# code to create a HashSet
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a HashSet of odd numbers
HashSet<int> odd = new HashSet<int>();
// Inserting elements in HashSet
for (int i = 0; i < 5; i++) {
odd.Add(2 * i + 1);
}
// Displaying the elements in the HashSet
foreach(int i in odd)
{
Console.WriteLine(i);
}
}
}
Output:
1 3 5 7 9
HashSet collection is used for storing the unique value, because HashSet doesn’t contain the duplicate value.
HashSet<T> hset=new HashSet<T>();
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
HashSet<int> hset=new HashSet<int>();
Random rand=new Random();
for( int i=0; i<10; i++)
{
hset.Add(rand.Next(50,100));
}
Console.WriteLine('Duplicate data will not show in the list :');
foreach(var item in hset)
Console.WriteLine(item);
}
}
Duplicate data will not show in the list :
87
85
54
73
56
75
50