HashSet in C# with Examples

Learn via video courses
Topics Covered

Overview

In the world of C# programming, the HashSet data structure is a crucial tool for efficiently managing collections of unique elements. Part of the System.Collections.Generic namespace and integral to the .NET framework, HashSet offers swift access to its elements and proves invaluable when dealing with collections where the exclusion of duplicates is paramount. It functions as an unordered collection, preventing the storage of duplicate values, making it an excellent choice for tasks involving set operations like union, intersection, or difference. With a rich set of methods and operations, HashSet is designed to store a collection of unique elements efficiently. This characteristic ensures data integrity and quick access to distinct elements, which are vital in various applications. Importantly, HashSet doesn't maintain the order of elements, but rather focuses on the uniqueness of elements and rapid retrieval. This means you can't rely on the order of elements as you would in an array or list. In practical terms, HashSet is an excellent choice when you need to store a collection of items while ensuring each item's uniqueness, quickly check for the presence of particular elements, and perform set operations efficiently.

How to Create a HashSet in C#

Creating a HashSet in C# is straightforward and involves the following steps:

Step 1: Import the Required Namespace

Before you can work with HashSets, make sure to include the System.Collections.Generic namespace in your code. This namespace contains the HashSet class.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Step 2: Declare and Initialize a HashSet

You can declare and initialize a HashSet by specifying its type (e.g., int, string, custom objects) and using the new keyword to create an instance of HashSet.

In this example, we've created an empty HashSet of integers. You can replace int with any other data type or class as needed.

Step 3: Add Elements to the HashSet

To populate your HashSet, you can use the Add method to insert elements. Each element is automatically checked for duplicates, ensuring that only unique values are stored.

In this code snippet, we've added two integers to the numbers HashSet, and the duplicate value 42 is automatically filtered out.

Now, you have a HashSet named numbers with unique elements. You can use various methods and operations to work with this HashSet, including adding, removing, and performing set operations like union, intersection, and difference.

Example

Output:

In this example, we created a HashSet of integers, added a few numbers, including a duplicate, and then printed the elements. As you can see in the output, only the unique values (42 and 17) are present in the HashSet. The duplicate 42 is automatically filtered out, demonstrating the HashSet's capability to ensure uniqueness.

Working With HashSet in C#

A HashSet in C# offers a wide range of methods and operations for managing collections of unique elements efficiently. In this section, we'll explore some essential operations, starting with adding elements to a HashSet and handling duplicate elements.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Attempt to Insert a Duplicate Element in a HashSet

One of the primary features of a HashSet is its ability to automatically reject duplicate elements. Let's see this in action with an example:

Output:

In this example, we've created a HashSet called colors to store unique color names. Notice that we attempted to add "Red" twice. However, when we iterate through the HashSet and print its elements, you'll see that only one "Red" is present. HashSet automatically filters out duplicate elements, ensuring that each element in the collection is unique.

This behavior is particularly valuable when you want to maintain a collection of distinct values without the overhead of manually checking for duplicates.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

How to Remove Elements from the HashSet?

Removing elements from a HashSet is straightforward using the Remove method. Let's look at an example:

Output:

In this example, we've created a HashSet called numbers and added three integers to it. We then removed the element 10 using the Remove method. When we print the elements of the HashSet, you can see that 10 has been successfully removed.

These basic operations demonstrate the simplicity and power of HashSet in C# for managing collections of unique elements. In the upcoming sections, we'll explore more advanced set operations that HashSet offers, such as union, intersection, and difference.

Set Operations in HashSet

HashSet in C# provides a set of powerful set operations that allow you to combine, compare, and manipulate collections of unique elements. In this section, we will explore three fundamental set operations: UnionWith, IntersectWith, and ExceptWith.

UnionWith

The UnionWith method combines two HashSets, creating a new HashSet containing all the unique elements from both sets. Let's see an example:

Output:

In this example, we created two HashSets, set1 and set2, each containing unique integers. By using the UnionWith method, we combined set1 and set2, resulting in a new HashSet, set1, that contains all unique elements from both sets. The resulting set1 includes elements 1 through 6, with duplicates automatically removed.

IntersectWith

The IntersectWith method, on the other hand, finds the common elements between two HashSets and updates the first HashSet with these elements. Here's an example:

Output:

In this example, we have set1 and set2, each containing unique integers. Using the IntersectWith method, we found the common elements between the two sets, which are 3 and 4. set1 was then updated to only contain these common elements.

ExceptWith

The ExceptWith method subtracts the elements of one HashSet from another, modifying the first HashSet with the result. Here's an example:

Output:

In this example, we have set1 and set2, each containing unique integers. The ExceptWith method subtracts the elements in set2 from set1, resulting in set1 containing only the elements that are exclusive to it, which are 1 and 2.

These set operations in HashSet are invaluable for performing various tasks, such as combining, comparing, or filtering collections of unique elements, and simplifying complex operations in your C# programs.

Conclusion

  • HashSet in C# is a valuable data structure for efficiently managing collections of unique elements.
  • It belongs to the System.Collections.Generic namespace and is widely used in .NET programming.
  • HashSet ensures that no duplicate values are stored in the collection, making it ideal for maintaining data integrity.
  • Common operations include adding, removing, and checking for the existence of elements.
  • HashSet provides powerful set operations like UnionWith, IntersectWith, and ExceptWith for combining, comparing, and manipulating sets efficiently.
  • These set operations simplify tasks involving set theory, such as finding intersections or differences between collections.
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more