How to use HashSet in C# (2024)

Take advantage of high-performance HashSet collections for storing unique elements to speed up searches in your applications.

How to use HashSet in C# (1)

Credit: Thinkstock

A HashSet is an optimized collection of unordered, unique elements that provides fast lookups and high-performance set operations. The HashSet class was first introduced in .NET 3.5 and is part of the System.Collection.Generic namespace. This article talks about how we can work with HashSets in C#.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core Console Application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core Console Application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with HashSet in the subsequent sections of this article.

What is a HashSet?

A HashSet — represented by the HashSet class pertaining to the System.Collections.Generic namespace — is a high-performance, unordered collection of unique elements. Hence a HashSet is not sorted and doesn’t contain any duplicate elements. A HashSet also doesn’t support indices — you can use enumerators only. A HashSet is usually used for high-performance operations involving a set of unique data.

The HashSet class implements several interfaces as shown below:

public class HashSet<T> : System.Collections.Generic.ICollection<T>,System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>,System.Collections.Generic.ISet<T>,System.Runtime.Serialization.IDeserializationCallback,System.Runtime.Serialization.ISerializable

Since HashSet contains only unique elements, its internal structure is optimized for faster searches. Note that you can store a single null value in a HashSet. So, HashSet is a good choice when you want a collection that contains unique elements and the elements in the collection can be searched quickly.

Search an item in a HashSet in C#

To search an item in a HashSet you can use the Contains method as shown in the code snippet given below:

static void Main(string[] args) { HashSet<string> hashSet = new HashSet<string>(); hashSet.Add("A"); hashSet.Add("B"); hashSet.Add("C"); hashSet.Add("D"); if (hashSet.Contains("D")) Console.WriteLine("The required element is available."); else Console.WriteLine("The required element isn’t available."); Console.ReadKey(); }

HashSet elements are always unique

If you attempt to insert a duplicate element in a HashSet it would simply be ignored but no runtime exception will be thrown. The following code snippet illustrates this.

static void Main(string[] args){ HashSet<string> hashSet = new HashSet<string>(); hashSet.Add("A"); hashSet.Add("B"); hashSet.Add("C"); hashSet.Add("D"); hashSet.Add("D"); Console.WriteLine("The number of elements is: {0}", hashSet.Count); Console.ReadKey();}

When you execute the program, the output will be as shown in Figure 1.

How to use HashSet in C# (2) IDG

Now consider the following code snippet that illustrates how duplicate elements are eliminated:

string[] cities = new string[] { "Delhi", "Kolkata", "New York", "London", "Tokyo", "Washington", "Tokyo" }; HashSet<string> hashSet = new HashSet<string>(cities); foreach (var city in hashSet) { Console.WriteLine(city); }

When you execute the above program, the duplicate city names would be removed.

How to use HashSet in C# (3) IDG

Remove elements from a HashSet in C#

To remove an item from a HashSet you should call the Remove method. The syntax of the Remove method is given below.

public bool Remove (T item);

If the item is found in the collection, the Remove method removes an element from the HashSet and returns true on success, false otherwise.

The code snippet given below illustrates how you can use the Remove method to remove an item from a HashSet.

string item = "D";if(hashSet.Contains(item)){ hashSet.Remove(item);}

To remove all items from a HashSet you can use the Clear method.

Use HashSet set operations methods in C#

HashSet has a number of important methods for set operations such as IntersectWith, UnionWith, IsProperSubsetOf, ExceptWith, and SymmetricExceptWith.

IsProperSubsetOf

The IsProperSubsetOf method is used to determine if a HashSet instance is a proper subset of a collection. This is illustrated in the code snippet given below.

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D" };HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X" };HashSet<string> setC = new HashSet<string>() { "A", "B", "C", "D", "E" };if (setA.IsProperSubsetOf(setC)) Console.WriteLine("setC contains all elements of setA.");if (!setA.IsProperSubsetOf(setB)) Console.WriteLine("setB does not contains all elements of setA.");

When you execute the above program, you should see the following output at the console window.

How to use HashSet in C# (4) IDG

UnionWith

The UnionWith method is used for set addition as illustrated in the code snippet given below.

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };setA.UnionWith(setB);foreach(string str in setA){ Console.WriteLine(str);}

When you execute the above piece of code, the elements of setB are copied into setA. So setA will now include “A”, “B”, “C”, “D”, “E”, “X”, and “Y”.

IntersectWith

The IntersectWith method is used to represent the intersection of two HashSets. Here’s an example to understand this.

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y"};setA.IntersectWith(setB);foreach (string str in setA){ Console.WriteLine(str);}

When you run the above program, only the elements common to the two HashSets will be displayed at the console window. The output would look like this:

How to use HashSet in C# (5) IDG

ExceptWith

The ExceptWith method represents mathematical set subtraction and is an O(n) operation. Assume you have two HashSets setA and setB and you specify the following statement:

setA.ExceptWith(setB);

This would return the elements of setA that are not present in setB. Let’s understand this with another example. Consider the code snippet given below.

HashSet setA = new HashSet() { "A", "B", "C", "D", "E" };HashSet setB = new HashSet() { "A", "X", "C", "Y" };setA.ExceptWith(setB);foreach (string str in setA){ Console.WriteLine(str);}

When you execute the above program, the elements “B”, “D”, and “E” will be printed at the console window as shown in Figure 5.

How to use HashSet in C# (6) IDG

SymmetricExceptWith

The SymmetricExceptWith method is used to modify a HashSet to contain only the unique elements of two HashSets, i.e., the elements that are not common to both HashSets. Consider the following code snippet that illustrates this.

HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };setA.SymmetricExceptWith(setB);foreach (string str in setA){ Console.WriteLine(str);}

When you execute the above code, only the unique elements of setA and setB — i.e., the elements that are present in setA but not in setB, and the elements that are present in setB but not in setA — will be displayed at the console window as shown in Figure 6.

How to use HashSet in C# (7) IDG

While the average complexity for accessing an element in an array is O(n), where n represents the number of elements in the array, the complexity is just O(1) for accessing a particular element in a HashSet.This makes HashSet a good choice for fast searches and for performing set operations. You can use a List if you would like to store a collection of items in a certain order, and maybe include duplicates as well.

How to do more in C#:

  • How to use named and optional parameters in C#
  • How to benchmark C# code using BenchmarkDotNet
  • How to use fluent interfaces and method chaining in C#
  • How to unit test static methods in C#
  • How to refactor God objects in C#
  • How to use ValueTask in C#
  • How to use immutability in C
  • How to use const, readonly, and static in C#
  • How to use data annotations in C#
  • How to work with GUIDs in C# 8
  • When to use an abstract class vs. interface in C#
  • How to work with AutoMapper in C#
  • How to use lambda expressions in C#
  • How to work with Action, Func, and Predicate delegates in C#
  • How to work with delegates in C#
  • How to implement a simple logger in C#
  • How to work with attributes in C#
  • How to work with log4net in C#
  • How to implement the repository design pattern in C#
  • How to work with reflection in C#
  • How to work with filesystemwatcher in C#
  • How to perform lazy initialization in C#
  • How to work with MSMQ in C#
  • How to work with extension methods in C#
  • How to us lambda expressions in C#
  • When to use the volatile keyword in C#
  • How to use the yield keyword in C#
  • How to implement polymorphism in C#
  • How to build your own task scheduler in C#
  • How to work with RabbitMQ in C#
  • How to work with a tuple in C#
  • Exploring virtual and abstract methods in C#
  • How to use the Dapper ORM in C#
  • How to use the flyweight design pattern in C#

Related content

  • feature9 hacks for a better nightly build The build pipeline is the engine of your software development lifecycle, so it pays to keep it tuned up and running right. Here are nine newer and better ways to build code.By Peter WaynerSep 16, 202411 minsCI/CDJavaPython
  • feature3 common misconceptions around biometrics and authentication Biometric authentication isn’t invulnerable, but it’s significantly more secure than traditional passwords. Here’s why. By Rishi BhargavaSep 16, 20248 minsBiometricsMulti-factor AuthenticationApplication Security
  • newsAWS hands OpenSearch to the Linux Foundation Open-source fork of Elasticsearch and Kibana will be supported by the newly formed OpenSearch Software Foundation, whose members include AWS, Uber, Canonical, and Aiven. By Paul KrillSep 16, 20242 minsAmazon Web ServicesOpen SourceCloud Computing
  • analysisLife without Python’s ‘dead batteries’ Python 3.13 is coming soon, and it will leave Python’s ‘dead batteries’ behind. Now’s the time to learn how to live without them. Also, get started with Pillow, enums, and the 'ast' library.By Serdar YegulalpSep 13, 20242 minsWeb DevelopmentPythonData Science
  • Resources
  • Videos
How to use HashSet in C# (2024)
Top Articles
Farm Credit Administration (FCA) | USAGov
[Free] How to Hide Text Messages on iPhone and Android
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
How To Cut Eelgrass Grounded
Pac Man Deviantart
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Umn Biology
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
San Pedro Sula To Miami Google Flights
Selly Medaline
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 6344

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.