Overview of HashSet in C#

In this article, you will get answers to the following questions.

  • What is HashSet?
  • Which version onwards supports the HashSet collection object?
  • Difference between List and HashSet.
  • Example of HashSet – Add, Delete, Iteration, Search.
  • Verify and check whether Element/Item is added or not.

HashSet is a collection object. HashSet is available or can be used from .Net Framework version 3.5 onwards. HashSet stores unique values in collection and supports ADD, EDIT and DELETE, SEARCH and COUNT operations and many more.

HashSet Use System. Collection. Generic namespace

Hashset Use System

For more information on HashSet refer to the following link.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=net-8.0

List vs HashSet

HASHSET LIST
Element/Item not able accessed by an integer index. Element/Item can be accessed by integer index.
Block the duplicate element/item in the collection. Duplicate items can be stored in a list collection.
HashSet support ICollection. List support
HashSets are more memory-efficient when it comes to storing unique elements because they don't maintain order. Lists are generally more memory-intensive as they maintain an ordered collection of elements.

HashSet supports the following collection interfaces

ICollection

IEnumerable

ISet

IReadOnlyCollection

The list supports the following collection interfaces.

ICollection

IEnumerable

IList

IReadOnlyCollection

IReadOnlyList

Faster access and search as compared to List. Slow access and search as compared to HashSet.

Example of HashSet

HashSet<string> FriendList = new HashSet<string>();

// Adding elements
FriendList.Add("Rajesh");
FriendList.Add("Mahesh");
FriendList.Add("Suresh");
FriendList.Add("Jayesh");

// Try to add Jayesh again
FriendList.Add("Jayesh");

Console.WriteLine("Add Rajesh");
Console.WriteLine("Add Mahesh");
Console.WriteLine("Add Suresh");
Console.WriteLine("Try to add Jayesh again");
Console.WriteLine("Add Jayesh");

Console.WriteLine("Total Element/Item in the collection: " + FriendList.Count.ToString());
Console.WriteLine("=====================================");

Console.WriteLine("-------------------------------------");
Console.WriteLine("Searching SURESH");
Console.WriteLine("-------------------------------------");

// Checking for an element
if (FriendList.Contains("Suresh"))
{
    Console.WriteLine("Suresh is in the collection.");
}
Console.WriteLine("=====================================");

// Removing Suresh from the list
FriendList.Remove("Suresh");

// Iterating over the HashSet collection
foreach (string friend in FriendList)
{
    Console.WriteLine(friend);
}

Output

Output

Verify and Check whether the Element is added or not.

Element

Happy Coding!

Up Next
    Ebook Download
    View all
    Learn
    View all