The Wayback Machine - https://web.archive.org/web/20240906205625/https://www.geeksforgeeks.org/c-sharp-hashset-class/
Open In App

C# | HashSet Class

Last Updated : 20 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
C# | Check if a HashSet is a proper subset of the specified collection
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. HashSet&lt;T>.IsProperSubsetOf(IEnumerable&lt;T>) method is
2 min read
C# | Check if a HashSet is a superset of the specified collection
Sure, here's an example code that demonstrates using the IsSupersetOf method to check if a HashSet&lt;string&gt; is a superset of a List&lt;string&gt; and then printing out a message indicating the result: C/C++ Code using System; using System.Collections.Generic; public class Program { public static void Main() { // create a HashSet of strings Has
3 min read
C# | Remove the specified element from a 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. HashSet&lt;T&gt;.Remove(T) method is used to remove the spe
3 min read
C# | Remove elements from a HashSet with conditions defined by the predicate
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. HashSet&lt;T>.RemoveWhere(Predicate&lt;T>) method is used t
3 min read
C# | Create HashSet from another collection
In C#, you can create a HashSet&lt;T&gt; from another collection by using the HashSet&lt;T&gt; constructor that takes an IEnumerable&lt;T&gt; parameter. Here's an example: C/C++ Code using System; using System.Collections.Generic; public class Program { public static void Main() { // create a List of integers List&lt;int&gt; numbers = new List&lt;i
2 min read
C# | Check if two HashSet&lt;T&gt; objects are equal
Equals(Object) Method which is inherited from the Object class is used to check if a specified HashSet&lt;T&gt; object is equal to another HashSet&lt;T&gt; object or not. Syntax: public virtual bool Equals (object obj); Here, obj is the object which is to be compared with the current object. Return Value: This method return true if the specified ob
2 min read
C# | Getting an enumerator that iterates through HashSet&lt;T&gt;
HashSet&lt;T&gt;.GetEnumerator Method is used to get an enumerator that iterates through a HashSet object. Syntax: public System.Collections.Generic.HashSet&lt;T&gt;.Enumerator GetEnumerator (); Return Value: It returns a HashSet&lt;T&gt;.Enumerator object for the HashSet&lt;T&gt; object. Below programs illustrate the use of above-discussed method:
2 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Program to Inherit an Abstract Class and Interface in the Same Class
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must imp
3 min read
C# | How to get TypeCode for the class String
GetTypeCode() method is used to get the TypeCode of the specified string. Here TypeCode enum represents a specific type of object. In TypeCode every data type is represented by a specific number like String is represented by 18, Int32 is represented by 9, etc. Syntax: public TypeCode GetTypeCode (); Return value: This method return an enumerated co
2 min read
C# | Class and Object
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheri
5 min read
C# | Sealed Class
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class. The following is the syntax of a sealed class : sealed class class_name { // data members
4 min read
C# | Math Class Fields with Examples
In C#, the Math class provides the constants and the static methods for logarithmic, trigonometric, and other mathematical functions. Math class has two fields as follows: Math.E FieldMath.PI FieldMath.E Field This field represents the natural logarithmic base, specified by the constant, e. Syntax: public const double E Program 1: To illustrate the
3 min read
C# | Math Class
In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class. public static class Math Fields A field is a variable that is declared in a class or struct. These are considered as the m
4 min read
C# | List Class
.list-table { border-collapse: collapse; width: 100%; } .list-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .list-table th { border: 1px solid #5fb962; padding: 8px; } .list-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .list-table tr:nth-child(odd) { background-color: #ffffff; } List&lt;T
7 min read
C# | ListDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } ListDictiona
5 min read
C# | HybridDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } HybridDictio
5 min read
C# | ArrayList Class
.arraylist-table { border-collapse: collapse; width: 100%; } .arraylist-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .arraylist-table th { border: 1px solid #5fb962; padding: 8px; } .arraylist-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .arraylist-table tr:nth-child(odd) { background-color
7 min read
C# | BitArray Class
.bitarray-table { border-collapse: collapse; width: 100%; } .bitarray-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .bitarray-table th { border: 1px solid #5fb962; padding: 8px; } .bitarray-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .bitarray-table tr:nth-child(odd) { background-color: #ff
6 min read
C# | StringDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } StringDictio
5 min read