top
April flash sale

Search

C# Tutorial

An unordered collection of unique items is known as a HashSet. It is found in System.Collections.Generic namespace. Some of the features of HashSet Collection are as follows:The HashSet Collection provides operations with high performance.There are no duplicate elements in the HashSet Collection.There is no maximum capacity for the elements in the HashSet. The capacity increases as the number of number of elements increase.There is no particular order of the elements in the HashSet Collection.Constructors in HashSet CollectionThe different constructors and their description is given as follows:Table: Constructors in HashSet Collection in C#Source: MSDNConstructorsDescriptionHashSet <T>()This constructor initializes a new instance of HashSet <T> class. This instance is empty and it uses the default equality comparer.HashSet<T>(IEnumerable<T>)This constructor initializes a new instance of HashSet <T> class. It contains elements copied from the specified collection with a capacity to accomodate all elements copied.IEqualityComparer<T>)HashSet <T> class. It uses the specified equality comparer that contains elements from the specified collection.HashSet<T>(IEqualityComparer<T>)This constructor initializes a new instance of HashSet <T> class. This instance is empty and it uses the specified equality comparer.HashSet<T>(IEnumerable<T>,HashSet<T>(Int32)This constructor initializes a new instance of HashSet <T> class. This instance is empty but it has a reserved space for capacity items. It uses the default equality comparer.HashSet<T>(Int32, IEqualityComparer<T>)This constructor initializes a new instance of HashSet <T> class. It can accomodate the capacity elements and uses the specified quality compare.HashSet<T>(SerializationInfo, StreamingContext)This constructor initializes a new instance of HashSet <T> class using serialized data.Properties in HashSet CollectionThe different properties and their description is given as follows:Table: Properties in HashSet Collection in C#Source: MSDNPropertiesDescriptionComparerThis property gets the IEqualityComparer<T> object. This object is used to determine equality for the values in the set.CountThis property gets the number of elements that are contained in a set.Methods in HashSet CollectionThe different methods and their description is given as follows:Table: Methods in HashSet Collection in C#Source: MSDNMethodsDescriptionAdd(T)This method adds the specified element to the set.Clear()This method removes all the elements from a HashSet<T> object.Contains(T)This method determines whether a HashSet<T> object contains the specified element.CopyTo(T[])This method copies the elements of a HashSet<T> object to an array.CreateSetComparer()This method returns an IEqualityComparer object. this object can be used for the equality testing of a HashSet<T> object.Equals(Object)This method determines if the specified object is equal to the current object or not.GetEnumerator()This method returns an enumerator that iterates through a HashSet<T> object.GetHashCode()This method is the default hash function.GetType()This method gets the Type of the current instance.IntersectWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain only those elements that are present in that object and in the specified collection.MemberwiseClone()This method creates a shallow copy of the current Object.Remove(T)This method removes the specified element from the HashSet<T> object.RemoveWhere(Predicate<T>)This method removes all the elements that match the conditions that are defined by a specified predicate from a HashSet<T> collection.SetEquals(IEnumerable<T>)This method determines if a HashSet<T> object and the specified collection contain the same elements.SymmetricExceptWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain only those elements that are present either in that object or in the specified collection, but not in both.ToString()This method returns a string that represents the current object.TrimExcess()This method sets the capacity of a HashSet<T> object to the actual number of elements that it contains, rounded up to a nearby, implementation-specific value.TryGetValue(T, T)This method searches the set for a given value and returns the equal value if it finds it.UnionWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain all the elements that are present in itself, the specified collection, or both.HashSet OperationsSome of the operations in a HashSet are given as follows:Adding Elements in HashSetThe Add() method can be used to add elements into a HashSet. The program that demonstrates this is given as follows:Source Code: Program to add elements in HashSet in C#using System; using System.Collections.Generic; namespace HashSetDemo {        class Example      {         static void Main(string[] args)        {            HashSet<int> set1 = new HashSet<int>();            for (int i = 1; i <= 10; i++)            {                set1.Add(i);            }            Console.WriteLine("The first 10 natural numbers are:");            foreach (int i in set1)            {                Console.WriteLine(i);            }        }    } }The output of the above program is given below:The first 10 natural numbers are: 1 2 3 4 5 6 7 8 9 10Printing Elements of HashSetThe elements of the Hashset can be printed using the foreach loop. A program for this is given below:Source Code: Program to print elements in HashSet in C#using System; using System.Collections.Generic; namespace HashSetDemo {   class Example    { static void Main(string[] args)        {            HashSet<int> set1 = new HashSet<int>();            for (int i = 1; i <= 10; i++)            {                set1.Add(i);            }            Console.WriteLine("The even numbers in the HashSet are:");            foreach (int i in set1)            {                if(i%2 == 0)                {                    Console.WriteLine(i);                }            }        }    } }The output of the above program is given below:The even numbers in the HashSet are: 2 4 6 8 10Removing Elements from HashSetThe Remove() method can be used to remove elements from a HashSet. The program that demonstrates this is given as follows:Source Code: Program to remove elements in HashSet in C#using System; using System.Collections.Generic; namespace HashSetDemo {   class Example    { static void Main(string[] args)        {            HashSet<int> set1 = new HashSet<int>();            for (int i = 1; i <= 10; i++)            {                set1.Add(i);            }            Console.WriteLine("The elements in the HashSet are:");            foreach (int i in set1)            {                Console.WriteLine(i);            }            for (int i = 1; i <= 10; i++)            {                if(i%2 == 0)                {                    set1.Remove(i);                }            }            Console.WriteLine("The odd elements in the HashSet are:");            foreach (int i in set1)            {                Console.WriteLine(i);            }        }    } }The output of the above program is given below:The elements in the HashSet are: 1 2 3 4 5 6 7 8 9 10 The odd elements in the HashSet are: 1 3 5 7 9Finding an element in HashSetThe Contains method finds if an element is present in HashSet ot ot. If it is present, Contains() returns TRUE and otherwise it returns FALSE.The program that demonstrates this is given as follows:Source Code: Program to find element in HashSet in C#using System; using System.Collections.Generic; namespace HashSetDemo {   class Example    { static void Main(string[] args)        {            HashSet<int> set1 = new HashSet<int>();            for (int i = 1; i <= 10; i++)            {                set1.Add(i);            }            Console.WriteLine("The elements in the HashSet are:");            foreach (int i in set1)            {                Console.WriteLine(i);            }            Console.WriteLine("5 is present in HashSet: " + set1.Contains(5));            Console.WriteLine("50 is present in HashSet: " + set1.Contains(50));        }    } }The output of the above program is given below:The elements in the HashSet are: 1 2 3 4 5 6 7 8 9 10 5 is present in HashSet: True 50 is present in HashSet: False
logo

C# Tutorial

HashSet Collection in C#

An unordered collection of unique items is known as a HashSet. It is found in System.Collections.Generic namespace. Some of the features of HashSet Collection are as follows:

  1. The HashSet Collection provides operations with high performance.
  2. There are no duplicate elements in the HashSet Collection.
  3. There is no maximum capacity for the elements in the HashSet. The capacity increases as the number of number of elements increase.
  4. There is no particular order of the elements in the HashSet Collection.

Constructors in HashSet Collection

The different constructors and their description is given as follows:

Table: Constructors in HashSet Collection in C#

Source: MSDN

ConstructorsDescription
HashSet <T>()This constructor initializes a new instance of HashSet <T> class. This instance is empty and it uses the default equality comparer.
HashSet<T>(IEnumerable<T>)This constructor initializes a new instance of HashSet <T> class. It contains elements copied from the specified collection with a capacity to accomodate all elements copied.
IEqualityComparer<T>)
HashSet <T> class. It uses the specified equality comparer that contains elements from the specified collection.
HashSet<T>(IEqualityComparer<T>)This constructor initializes a new instance of HashSet <T> class. This instance is empty and it uses the specified equality comparer.
HashSet<T>(IEnumerable<T>,
HashSet<T>(Int32)
This constructor initializes a new instance of HashSet <T> class. This instance is empty but it has a reserved space for capacity items. It uses the default equality comparer.
HashSet<T>(Int32, IEqualityComparer<T>)This constructor initializes a new instance of HashSet <T> class. It can accomodate the capacity elements and uses the specified quality compare.
HashSet<T>(SerializationInfo, StreamingContext)
This constructor initializes a new instance of HashSet <T> class using serialized data.

Properties in HashSet Collection

The different properties and their description is given as follows:

Table: Properties in HashSet Collection in C#

Source: MSDN

PropertiesDescription
ComparerThis property gets the IEqualityComparer<T> object. This object is used to determine equality for the values in the set.
CountThis property gets the number of elements that are contained in a set.

Methods in HashSet Collection

The different methods and their description is given as follows:

Table: Methods in HashSet Collection in C#

Source: MSDN

MethodsDescription
Add(T)This method adds the specified element to the set.
Clear()This method removes all the elements from a HashSet<T> object.
Contains(T)This method determines whether a HashSet<T> object contains the specified element.
CopyTo(T[])This method copies the elements of a HashSet<T> object to an array.
CreateSetComparer()
This method returns an IEqualityComparer object. this object can be used for the equality testing of a HashSet<T> object.
Equals(Object)This method determines if the specified object is equal to the current object or not.
GetEnumerator()This method returns an enumerator that iterates through a HashSet<T> object.
GetHashCode()This method is the default hash function.
GetType()This method gets the Type of the current instance.
IntersectWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain only those elements that are present in that object and in the specified collection.
MemberwiseClone()This method creates a shallow copy of the current Object.
Remove(T)This method removes the specified element from the HashSet<T> object.
RemoveWhere(Predicate<T>)This method removes all the elements that match the conditions that are defined by a specified predicate from a HashSet<T> collection.
SetEquals(IEnumerable<T>)This method determines if a HashSet<T> object and the specified collection contain the same elements.
SymmetricExceptWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain only those elements that are present either in that object or in the specified collection, but not in both.
ToString()This method returns a string that represents the current object.
TrimExcess()This method sets the capacity of a HashSet<T> object to the actual number of elements that it contains, rounded up to a nearby, implementation-specific value.
TryGetValue(T, T)This method searches the set for a given value and returns the equal value if it finds it.
UnionWith(IEnumerable<T>)This method modifies the current HashSet<T> object to contain all the elements that are present in itself, the specified collection, or both.

HashSet Operations

Some of the operations in a HashSet are given as follows:

Adding Elements in HashSet

The Add() method can be used to add elements into a HashSet. The program that demonstrates this is given as follows:

Source Code: Program to add elements in HashSet in C#

using System;
using System.Collections.Generic;
namespace HashSetDemo
{   
    class Example
     {
        static void Main(string[] args)
       {
           HashSet<int> set1 = new HashSet<int>();

           for (int i = 1; i <= 10; i++)
           {
               set1.Add(i);
           }

           Console.WriteLine("The first 10 natural numbers are:");
           foreach (int i in set1)
           {
               Console.WriteLine(i);
           }
       }
   }
}

The output of the above program is given below:

The first 10 natural numbers are:
1
2
3
4
5
6
7
8
9
10

Printing Elements of HashSet

The elements of the Hashset can be printed using the foreach loop. A program for this is given below:

Source Code: Program to print elements in HashSet in C#

using System;
using System.Collections.Generic;
namespace HashSetDemo
{   class Example
   { static void Main(string[] args)
       {
           HashSet<int> set1 = new HashSet<int>();
           for (int i = 1; i <= 10; i++)
           {
               set1.Add(i);
           }
           Console.WriteLine("The even numbers in the HashSet are:");
           foreach (int i in set1)
           {
               if(i%2 == 0)
               {
                   Console.WriteLine(i);
               }
           }
       }
   }
}

The output of the above program is given below:

The even numbers in the HashSet are:
2
4
6
8
10

Removing Elements from HashSet

The Remove() method can be used to remove elements from a HashSet. The program that demonstrates this is given as follows:

Source Code: Program to remove elements in HashSet in C#

using System;
using System.Collections.Generic;
namespace HashSetDemo
{   class Example
   { static void Main(string[] args)
       {
           HashSet<int> set1 = new HashSet<int>();

           for (int i = 1; i <= 10; i++)
           {
               set1.Add(i);
           }
           Console.WriteLine("The elements in the HashSet are:");
           foreach (int i in set1)
           {
               Console.WriteLine(i);
           }
           for (int i = 1; i <= 10; i++)
           {
               if(i%2 == 0)
               {
                   set1.Remove(i);
               }
           }
           Console.WriteLine("The odd elements in the HashSet are:");
           foreach (int i in set1)
           {
               Console.WriteLine(i);
           }
       }
   }
}

The output of the above program is given below:

The elements in the HashSet are:
1
2
3
4
5
6
7
8
9
10
The odd elements in the HashSet are:
1
3
5
7
9

Finding an element in HashSet

The Contains method finds if an element is present in HashSet ot ot. If it is present, Contains() returns TRUE and otherwise it returns FALSE.

The program that demonstrates this is given as follows:

Source Code: Program to find element in HashSet in C#

using System;
using System.Collections.Generic;
namespace HashSetDemo
{   class Example
   { static void Main(string[] args)
       {
           HashSet<int> set1 = new HashSet<int>();
           for (int i = 1; i <= 10; i++)
           {
               set1.Add(i);
           }
           Console.WriteLine("The elements in the HashSet are:");
           foreach (int i in set1)
           {
               Console.WriteLine(i);
           }
           Console.WriteLine("5 is present in HashSet: " + set1.Contains(5));
           Console.WriteLine("50 is present in HashSet: " + set1.Contains(50));
       }
   }
}

The output of the above program is given below:

The elements in the HashSet are:
1
2
3
4
5
6
7
8
9
10

5 is present in HashSet: True
50 is present in HashSet: False

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial