Open In App

C# | HashSet Class

Last Updated : 20 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.
  • The capacity of a HashSet<T> object is the number of elements that the object can hold.
  • A HashSet<T> object’s capacity automatically increases as elements are added to the object.
  • A HashSet<T> collection is not sorted and cannot contain duplicate elements.
  • HashSet<T> provides many mathematical set operations, such as set addition (unions) and set subtraction.

Constructors

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

Properties

Property Description
Comparer Gets the IEqualityComparer object that is used to determine equality for the values in the set.
Count Gets the number of elements that are contained in a set.

Example:




// 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

Methods

Method Description
Add(T) Adds the specified element to a set.
Clear() Removes all elements from a HashSet object.
Contains(T) Determines whether a HashSet object contains the specified element.
CopyTo() Copies the elements of a HashSet collection to an array.
CreateSetComparer() Returns an IEqualityComparer object that can be used for equality testing of a HashSet object.
Equals(Object) Determines whether the specified object is equal to the current object.
ExceptWith(IEnumerable) Removes all elements in the specified collection from the current HashSet object.
GetEnumerator() Returns an enumerator that iterates through a HashSet object.
GetHashCode() Serves as the default hash function.
GetObjectData(SerializationInfo, StreamingContext) Implements the ISerializable interface and returns the data needed to serialize a HashSet object.
GetType() Gets the Type of the current instance.
IntersectWith(IEnumerable) Modifies the current HashSet object to contain only elements that are present in that object and in the specified collection.
IsProperSubsetOf(IEnumerable) Determines whether a HashSet object is a proper subset of the specified collection.
IsProperSupersetOf(IEnumerable) Determines whether a HashSet object is a proper superset of the specified collection.
IsSubsetOf(IEnumerable) Determines whether a HashSet object is a subset of the specified collection.
IsSupersetOf(IEnumerable) Determines whether a HashSet object is a superset of the specified collection.
MemberwiseClone() Creates a shallow copy of the current Object.
OnDeserialization(Object) Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
Overlaps(IEnumerable) Determines whether the current HashSet object and a specified collection share common elements.
Remove(T) Removes the specified element from a HashSet object.
RemoveWhere(Predicate) Removes all elements that match the conditions defined by the specified predicate from a HashSet collection.
SetEquals(IEnumerable) Determines whether a HashSet object and the specified collection contain the same elements.
SymmetricExceptWith(IEnumerable) Modifies the current HashSet object to contain only elements that are present either in that object or in the specified collection, but not both.
ToString() Returns a string that represents the current object.
TrimExcess() Sets the capacity of a HashSet object to the actual number of elements it contains, rounded up to a nearby, implementation-specific value.
TryGetValue(T, T) Searches the set for a given value and returns the equal value it finds, if any.
UnionWith(IEnumerable) Modifies the current HashSet object to contain all elements that are present in itself, the specified collection, or both.

Example:




// C# code to Check if a HashSet is
// a subset of the specified collection
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet1 = new HashSet<int>();
  
        // Inserting elements in HashSet
        // mySet1 only contains even numbers less than
        // equal to 10
        for (int i = 1; i <= 5; i++)
            mySet1.Add(2 * i);
  
        // Creating a HashSet of integers
        HashSet<int> mySet2 = new HashSet<int>();
  
        // Inserting elements in HashSet
        // mySet2 contains all numbers from 1 to 10
        for (int i = 1; i <= 10; i++)
            mySet2.Add(i);
  
        // Check if a HashSet mySet1 is a subset
        // of the HashSet mySet2
        Console.WriteLine(mySet1.IsSubsetOf(mySet2));
    }
}


Output:

True

Example:




// C# code to check if a HashSet
// contains the specified element
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of strings
        HashSet<string> mySet = new HashSet<string>();
  
        // Inserting elements in HashSet
        mySet.Add("DS");
        mySet.Add("C++");
        mySet.Add("Java");
        mySet.Add("JavaScript");
  
        // Check if a HashSet contains
        // the specified element
        if (mySet.Contains("Java"))
            Console.WriteLine("Required Element is present");
        else
            Console.WriteLine("Required Element is not present");
    }
}


Output:

Required Element is present

Reference:



Similar Reads

C# | Remove all elements in a collection from a HashSet
In C#, you can use the ExceptWith() method to remove all the elements in a collection from a HashSet. The ExceptWith() method removes all the elements in the specified collection from the current HashSet. Here is an example code that demonstrates how to use the ExceptWith() method to remove all the elements in a collection from a HashSet: C/C++ Cod
3 min read
C# | Check if HashSet and the specified collection contain the same elements
Here's an example code that demonstrates how to use the Overlaps method to check if a HashSet and a specified collection share common elements in C#: C/C++ Code using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Create a HashSet and a List HashSet&lt;int&gt; set1 = new HashSet&lt;int&gt; { 1, 2, 3,
3 min read
C# | Check if a HashSet is a proper superset of the specified collection
A HashSet is an unordered collection of the unique elements. It comes under the 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. HashSet.IsProperSupersetOf(IEnumerable) Method is used
2 min read
C# | Check if a HashSet and a specified collection share common elements
In C#, you can use the SetEquals method to check if a HashSet and a specified collection contain the same elements. The SetEquals method returns true if the HashSet and the specified collection contain the same elements; otherwise, it returns false. Here is an example code that demonstrates how to use the SetEquals method to check if a HashSet and
3 min read
C# | Add element to HashSet
A HashSet 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. Elements can be added to HashSet using HashSet.Add(T) Metho
2 min read
C# | Union of two HashSet
A HashSet is an unordered collection of the unique elements. It comes under the 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. For the Union of two HashSet, HashSet.UnionWith(IEnumer
3 min read
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.Count Property to count the number of e
3 min read
C# | Check if a HashSet is a subset of the specified collection
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. HashSet.IsSubsetOf(IEnumerable) Method is used to check whe
2 min read
C# | Check if a HashSet contains the specified element
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. HashSet.Contains(T) Method is used to check whether a HashS
2 min read
C# | Remove all elements from a HashSet
A HashSet is an unordered collection of the unique elements. It comes under the 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. HashSet.Clear Method is used to remove all the elements
2 min read