Customise Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.

No cookies to display.

HashSet<T> in .NET 9

What is a HashSet<T>?

In .NET, a HashSet<T> is a collection that implements an unordered set of unique elements. Introduced in .NET Framework 3.5 as part of the generic collections library, HashSet<T> benefits from internal framework optimizations for performance. Conceptually, it uses a hash-based structure to efficiently store elements and ensure uniqueness, similar to how a dictionary uses hashes for keys.

In everyday programming, it’s commonly used when we need a list of unique elements. Its key benefits are:

  • Performance: Thanks to the use of a hash table, common operations like Contains have an average time complexity of O(1) (unlike searching through strings, which has a complexity of O(n) because the list needs to scan all existing elements).
  • Uniqueness: Perfect for data collections where duplicates must be avoided without manual checks. Duplicate entries are automatically discarded.

Practical Examples

Creating a HashSet<T>

Here are different ways to instantiate a HashSet<T>: passing an existing list to the constructor or adding elements incrementally.

C#
var stringList = new List<string> { "Alice", "Bob", "Giorgio" };
var hashSet1 = new HashSet<string>(stringList);

var intList = new List<int> { 1, 2, 3, 4, 5 };
var hashSet2 = new HashSet<int>(intList);

var hashSet3 = new HashSet<int>();
hashSet3.Add(1);
hashSet3.Add(2);
hashSet3.Add(3);
hashSet3.Add(4);

Merging two HashSet<T> lists

C#
var hashSet1 = new HashSet<int>(new List<int> { 1, 2, 3, 4, 5 });
var hashSet2 = new HashSet<int>(new List<int> { 5, 6, 7, 8, 9 });

hashSet1.UnionWith(hashSet2);

foreach (var item in hashSet1)
{
    Console.WriteLine(item);
}

/*
Output:

1
2
3
4
5
6
7
8
9

*/

Intersection of two HashSets

Finding common elements

C#
var hashSet1 = new HashSet<int>(new List<int> { 1, 2, 3, 4, 5 });
var hashSet2 = new HashSet<int>(new List<int> { 3, 4, 5, 6, 7 });

hashSet1.IntersectWith(hashSet2);

foreach (var item in hashSet1)
{
    Console.WriteLine(item);
}

/*
Output:

3
4
5

*/

Subset (ExceptWith)

Returning a HashSet<T>by removing elements present in another HashSet<T>:

C#
var hashSet1 = new HashSet<int>(new List<int> { 1, 2, 3, 4, 5 });
var hashSet2 = new HashSet<int>(new List<int> { 3, 4, 5, 6, 7 });

hashSet1.ExceptWith(hashSet2);

foreach (var item in hashSet1)
{
    Console.WriteLine(item);
}

/*
Output:

1
2

*/

Removing duplicates

When a HashSet<T> is initialized with a list containing duplicate strings, duplicates are automatically removed. Note that “Bob” and “bob” are considered distinct.

C#
var list = new List<string> { "Alice", "Bob", "Alice", "Alice", "Giorgio", "bob" };
var hashSet = new HashSet<string>(list);

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

/*
Output:

    Alice
    Bob
    Giorgio
    bob
    
*/

Conclusion

HashSet<T> is a powerful, high-performance, and versatile tool for managing collections of unique data in .NET. Its features and support for set operations simplify complex scenarios while improving performance.

Share this article
Shareable URL
Prev Post

Discovering Span<T>

Next Post

SOLID Programming Principles

Read next

LINQ Extension Method

At the 2024 edition of Overnet’s WPC conference, I attended an insightful talk about LINQ extension…

.NET 9 Hybrid Cache

In this article, we’ll delve into one of Microsoft’s latest innovations, currently in preview at the time of…

FluentValidation

Throughout my career as a developer, I’ve built, maintained, and extended hundreds of .NET applications.…
fluent validation article header