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
How to Decompress the Lower Back? | Premia Spine
Cryptocurrencies - Pakistan | Statista Market Forecast
Poe T4 Aisling
Joe Taylor, K1JT – “WSJT-X FT8 and Beyond”
Cappacuolo Pronunciation
Federal Fusion 308 165 Grain Ballistics Chart
Math Playground Protractor
St Petersburg Craigslist Pets
Southeast Iowa Buy Sell Trade
50 Meowbahh Fun Facts: Net Worth, Age, Birthday, Face Reveal, YouTube Earnings, Girlfriend, Doxxed, Discord, Fanart, TikTok, Instagram, Etc
877-668-5260 | 18776685260 - Robocaller Warning!
Notary Ups Hours
Mail Healthcare Uiowa
Top Golf 3000 Clubs
Infinite Campus Parent Portal Hall County
Cranberry sauce, canned, sweetened, 1 slice (1/2" thick, approx 8 slices per can) - Health Encyclopedia
Raid Guides - Hardstuck
Conduent Connect Feps Login
4156303136
24 Best Things To Do in Great Yarmouth Norfolk
Bfg Straap Dead Photo Graphic
Busby, FM - Demu 1-3 - The Demu Trilogy - PDF Free Download
Dr Adj Redist Cadv Prin Amex Charge
Vrachtwagens in Nederland kopen - gebruikt en nieuw - TrucksNL
Juicy Deal D-Art
College Basketball Picks: NCAAB Picks Against The Spread | Pickswise
Jc Green Obits
Pearson Correlation Coefficient
Company History - Horizon NJ Health
Walgreens Bunce Rd
Speedstepper
Ascensionpress Com Login
Publix Christmas Dinner 2022
Happy Shuttle Cancun Review
Salemhex ticket show3
Christmas Days Away
Poe T4 Aisling
Brenda Song Wikifeet
Mega Millions Lottery - Winning Numbers & Results
LEGO Star Wars: Rebuild the Galaxy Review - Latest Animated Special Brings Loads of Fun With An Emotional Twist
Nsu Occupational Therapy Prerequisites
Cdcs Rochester
The power of the NFL, its data, and the shift to CTV
Lady Nagant Funko Pop
Child care centers take steps to avoid COVID-19 shutdowns; some require masks for kids
Stitch And Angel Tattoo Black And White
Motorcycles for Sale on Craigslist: The Ultimate Guide - First Republic Craigslist
Aaca Not Mine
Vcuapi
The Significance Of The Haitian Revolution Was That It Weegy
Where To Find Mega Ring In Pokemon Radical Red
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.