{"id":76166,"date":"2022-11-02T08:00:02","date_gmt":"2022-11-02T07:00:02","guid":{"rendered":"https:\/\/code-maze.com\/?p=76166"},"modified":"2022-11-26T16:38:43","modified_gmt":"2022-11-26T15:38:43","slug":"csharp-hashset","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-hashset\/","title":{"rendered":"HashSet in C#"},"content":{"rendered":"<p>In this article, we are going to take a look at the HashSet class in C#. We will discuss how to use it and its key features. Also, we are going to see some examples of how to use it in practice. Finally, we&#8217;ll compare it to other data structures available in C#.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/collections-csharp\/HashSetInCSharp\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Without further ado, let&#8217;s start!<\/p>\n<h2><a id=\"what\"><\/a>What Is a HashSet in C#?<\/h2>\n<p><strong>A HashSet is a collection of unique elements that uses a<\/strong> <a href=\"https:\/\/code-maze.com\/csharp-queue-stack-hashtable\/#hashtable\" target=\"_blank\" rel=\"noopener\">hash table<\/a><strong> for storage, allowing faster retrieval of elements than other collection types<\/strong>. Adding and removing elements to the HashSet also has constant time complexity. However, it does not maintain insertion order and cannot access elements by index.<\/p>\n<p>The <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/api\/system.collections.generic.hashset-1?view=net-7.0\" target=\"_blank\" rel=\"nofollow noopener\">HashSet&lt;T&gt;<\/a> class has been available since .NET 3.5 as part of the <code>System.Collection.Generic<\/code> namespace and implements these interfaces:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class HashSet&lt;T&gt; : System.Collections.Generic.ICollection&lt;T&gt;,\r\nSystem.Collections.Generic.IEnumerable&lt;T&gt;, \r\nSystem.Collections.Generic.IReadOnlyCollection&lt;T&gt;,\r\nSystem.Collections.Generic.ISet&lt;T&gt;,\r\nSystem.Runtime.Serialization.IDeserializationCallback,\r\nSystem.Runtime.Serialization.ISerializable<\/pre>\n<h2><a id=\"how\"><\/a>How to Create a HashSet in C#<\/h2>\n<p>For most of our examples, we intend to use a HashSet that contains strings of some of the popular programming languages used today.<\/p>\n<p>Let&#8217;s start by creating an empty HashSet:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var languages = new HashSet&lt;string&gt;();<\/code><\/p>\n<h2><a id=\"add\"><\/a>Add Items to a HashSet<\/h2>\n<p>Let&#8217;s begin by adding a set of programming languages into our <code>HashSet&lt;string&gt;<\/code> object by taking advantage of the <code>Add()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public HashSet&lt;string&gt; ProgrammingLanguages() \r\n{\r\n    var languages = new HashSet&lt;string&gt;();\r\n\r\n    languages.Add(\"C\");\r\n    languages.Add(\"C++\");\r\n    languages.Add(\"C#\");\r\n    languages.Add(\"Java\");\r\n    languages.Add(\"Scala\");\r\n    languages.Add(\"TypeScript\");\r\n    languages.Add(\"Python\");\r\n    languages.Add(\"JavaScript\");\r\n    languages.Add(\"Rust\");\r\n\r\n    return languages;\r\n}<\/pre>\n<p>Here, we insert elements into the <code>languages<\/code> HashSet by invoking the <code>Add()<\/code> method.<\/p>\n<p>In some cases, we may want to initialize HashSets directly with values:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var languages = new HashSet&lt;string&gt; { \"C\", \"C++\", \"C#\", \"Java\" };<\/code><\/p>\n<p>For all our tests, we are going to reuse the same class object instance to make our examples as easy to follow as possible:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">HashSetsInCSharpMethods hashSet = new HashSetsInCSharpMethods();<\/code><\/p>\n<p>Let&#8217;s also initialize our HashSet in the test constructor to avoid repetitive code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">private readonly HashSet&lt;string&gt; _languages;\r\n\r\npublic HashSetInCSharpUnitTests()\r\n{\r\n    _languages = hashSet.ProgrammingLanguages();\r\n}<\/pre>\n<p>Next, we can verify that our HashSet has <strong>nine elements<\/strong> and check whether it <strong>contains one of the elements (&#8220;C#&#8221; )<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Assert.IsInstanceOfType(_languages, typeof(HashSet&lt;string&gt;));\r\nAssert.AreEqual(_languages.Count(), 9);\r\nAssert.IsTrue(_languages.Contains(\"C#\"));<\/pre>\n<p>We can successfully prove that <code>_languages<\/code> is of type <code>HashSet&lt;string&gt;<\/code>. We use the inbuilt <code>Count()<\/code> method to check the number of elements in our HashSet.<\/p>\n<p>Also, we use the inbuilt <code>Contains()<\/code> method to check if a HashSet has a specific element. The method takes the element as a parameter and returns a boolean value indicating whether or not the element is present in the set.<\/p>\n<p>This technique can be useful for quickly checking if an element exists in the set without having to iterate through all of the elements.<\/p>\n<h2><strong><a id=\"duplicates\"><\/a>Duplicate Elements in a HashSet<\/strong><\/h2>\n<p>HashSets do not allow for duplicate elements. It will not affect the set if we try to add a duplicate element. It uses a hashing structure that ensures that each element can only appear once in the set.<\/p>\n<p>Let&#8217;s attempt to add duplicate elements to the <code>_languages<\/code> HashSet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">_languages.Add(\"C\");\r\n_languages.Add(\"C++\");\r\n_languages.Add(\"C#\");\r\n\r\nAssert.IsInstanceOfType(_languages, typeof(HashSet&lt;string&gt;));\r\nAssert.AreEqual(_languages.Count(), 9);<\/pre>\n<p>When we try to add duplicate values to our <code>_languages<\/code> HashSet doesn&#8217;t get modified, as the set already contains those values. Therefore, its count remains nine instead of twelve.<\/p>\n<h2><strong><a id=\"accessing-elements\"><\/a>Retrieve HashSet Elements<\/strong><\/h2>\n<p>Besides using the inbuilt <code>Contains()<\/code> method to check whether a HashSet contains a specific value, we can use the inbuilt <code>TryGetValue (T equalVal, out T actualVal)<\/code> technique to achieve the same result. The method takes two parameters, the first being the value to search for and the next being what the search finds or the default value when the search doesn&#8217;t yield any results.\u00a0<\/p>\n<p>Let&#8217;s put this theory into practice:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Assert.IsTrue(_languages.TryGetValue(\"C#\", out _));\r\nAssert.IsTrue(_languages.Contains(\"C#\"));\r\nAssert.IsFalse(_languages.TryGetValue(\"Assembly\", out _));\r\nAssert.IsFalse(_languages.Contains(\"Assembly\"));<\/pre>\n<p>Here, <code>_languages<\/code> does not contain &#8220;Assembly&#8221; but contains &#8220;C#&#8221; and uses the discard operator to ignore the <code>TryGetValue()<\/code> method&#8217;s return value.\u00a0\u00a0<\/p>\n<h2><a id=\"remove\"><\/a>Remove Elements From a HashSet<\/h2>\n<p>To remove an item from the HashSet, we can use the <code>Remove()<\/code> method. Like the <a href=\"#add\">Add()<\/a> method,\u00a0 it takes the object as a parameter and removes it from the HashSet:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public HashSet&lt;string&gt; RemoveElement(HashSet&lt;string&gt; hashSet, string value) \r\n{\r\n    hashSet.Remove(value);\r\n\r\n    return hashSet;\r\n}<\/pre>\n<p>Here, the <code>RemoveElement()<\/code> method takes a <code>HashSet&lt;string&gt;<\/code> and a <code>string<\/code> as parameters and uses the <code>Remove()<\/code> method to remove an element before returning the updated HashSet.\u00a0<\/p>\n<p>Next, we can verify that the <code>RemoveElement()<\/code> method successfully removes elements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var elementToRemove = \"Java\";\r\n\r\nvar updatedLanguages = hashSet.RemoveElement(_languages, elementToRemove);\r\n\r\nAssert.IsFalse(updatedLanguages.Contains(elementToRemove));\r\nAssert.AreEqual(_languages.Count(), 8);<\/pre>\n<p>We invoke the <code>RemoveElement()<\/code> method and pass our HashSet, and a string (&#8220;Java&#8221;), which we can prove is removed as the updated HashSet does not contain that value, and its count decreases by one.\u00a0<\/p>\n<h3><a id=\"remove-where\"><\/a>RemoveWhere() Method<\/h3>\n<p>Besides using the inbuilt <code>Remove()<\/code> method, we can use the <code>RemoveWhere()<\/code> method that takes a <a href=\"https:\/\/code-maze.com\/delegates-charp\/\" target=\"_blank\" rel=\"noopener\">predicate<\/a> as a parameter to set conditions that determine whether we remove an element. To illustrate this concept, let&#8217;s implement a HashSet that stores unique random numbers:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public HashSet&lt;int&gt; RandomInts(int size) \r\n{\r\n    var rand = new Random();\r\n    var numbers = new HashSet&lt;int&gt;();\r\n\r\n    for (int i = 0; i &lt; size; i++) \r\n    {\r\n        numbers.Add(rand.Next());\r\n    }\r\n\r\n    return numbers;\r\n}<\/pre>\n<p>Our <code>RandomInts()<\/code> method takes the number of integers to generate as its sole input. It uses the inbuilt <a href=\"https:\/\/code-maze.com\/csharp-random-class\/\" target=\"_blank\" rel=\"noopener\">random<\/a> class to generate random numbers and inserts each value into a HashSet before returning it.\u00a0<\/p>\n<p>Next, let&#8217;s implement a method that returns true when an integer is odd. We are going to use this method as our predicate when we eventually implement the <code>RemoveWhereElement()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public bool IsOdd(int num) \r\n{\r\n    return num % 2 == 1;\r\n}<\/pre>\n<p>Finally, let&#8217;s implement our <code>RemoveWhereElement()<\/code> method by passing the predicate function <code>IsOdd()<\/code> as a parameter:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public HashSet&lt;int&gt; RemoveWhereElement(HashSet&lt;int&gt; hashSet)\r\n{\r\n    hashSet.RemoveWhere(IsOdd);\r\n\r\n    return hashSet;\r\n}<\/pre>\n<p>We can verify that the <code>RemoveWhereElement()<\/code> method removes all the odd numbers in the HashSet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var numbers = hashSet.RandomInts(100);\r\nvar oddNumbers = new HashSet&lt;int&gt;();\r\n\r\nforeach (var item in numbers) \r\n{\r\n    if (hashSet.IsOdd(item) == true) \r\n    {\r\n        oddNumbers.Add(item);\r\n    }\r\n}\r\n\r\nhashSet.RemoveWhereElement(numbers);\r\nvar testValue = oddNumbers.First();\r\nvar checkValue = hashSet.IsOdd(testValue);\r\n\r\nAssert.IsTrue(checkValue);\r\nAssert.IsFalse(oddNumbers.IsSubsetOf(numbers));\r\nAssert.AreEqual(numbers.Union(oddNumbers).Count(), 100);<\/pre>\n<p>Here, we create a HashSet to store odd numbers from the random numbers we generate. Next, we invoke the <code>RemoveWhereElement()<\/code> method to remove all odd numbers from <code>numbers<\/code> (contains all the numbers, including odd numbers). Then, we check whether the first element in the <code>oddNumbers<\/code> HashSet is an odd number. Finally, we assert that <code>oddNumbers<\/code> is not a subset of <code>numbers<\/code>, and verify that their union still adds up to 100 elements.\u00a0<\/p>\n<h3><a id=\"clear\"><\/a>Remove Elements From a HashSet Through the Clear() Method<\/h3>\n<p>What if we want to remove all the elements in a HashSet? We can make use of the <code>Clear()<\/code> inbuilt method.<\/p>\n<p>Let&#8217;s verify that the <code>Clear()<\/code> method removes all elements from the <code>_languages<\/code> HashSet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">_languages.Clear();\r\n\r\nAssert.AreEqual(0, _languages.Count());\r\nAssert.IsNull(_languages.FirstOrDefault());<\/pre>\n<p>After invoking the <code>Clear()<\/code> method, we can prove that we remove all the elements from the <code>_languages<\/code> HashSet as it has a count of zero.\u00a0\u00a0<\/p>\n<h2><a id=\"iterate\"><\/a>Iterate Through a HashSet in C#<\/h2>\n<p>To iterate through a HashSet, we can use the statements available in C# such as <code>for<\/code>, <code>foreach<\/code> and <code>while<\/code> loops to achieve our goals:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public List&lt;int&gt; CreateList(HashSet&lt;int&gt; hashSet)\r\n{\r\n    var list = new List&lt;int&gt;();\r\n\r\n    foreach (var item in hashSet) \r\n    {\r\n        list.Add(item);\r\n    }\r\n\r\n    return list;\r\n}<\/pre>\n<p>Here, the <code>CreateList()<\/code> method takes a<code>HashSet&lt;int&gt;<\/code> object as its sole parameter and adds all the elements to the list.<\/p>\n<p>Alternatively, we can simply call the inbuilt <code>ToList()<\/code> method to convert the HashSet into a list:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var list = hashSet.ToList();<\/pre>\n<p>Let&#8217;s verify that <code>CreateList()<\/code> successfully returns a populated <code>List&lt;int&gt;<\/code> object:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var numbers = hashSet.RandomInts(100);\r\n\r\nvar numbersList = hashSet.CreateList(numbers);\r\n\r\nCollectionAssert.AllItemsAreInstancesOfType(numbersList, typeof(int));\r\nAssert.AreEqual(numbersList.Count(), numbers.Count());<\/pre>\n<p>We must remember that a HashSet <strong>does not store elements in a specific order<\/strong>, so the order in which we iterate through the elements varies.<\/p>\n<h2><a id=\"set-operations\"><\/a>HashSet Set Operations Methods in C#<\/h2>\n<p>Let&#8217;s understand some methods we can use for set operations as we work with HashSets.<\/p>\n<h3><a id=\"subset\"><\/a>IsProperSubsetOf\/IsProperSuperSetOf<\/h3>\n<p>When we want to check whether a HashSet instance is a proper subset of another HashSet instance, we use the <code>IsProperSubsetOf()<\/code> method. Likewise, we can use the <code>IsProperSupersetOf()<\/code> method to determine if a HashSet is a superset of another HashSet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var moreLanguages = new HashSet&lt;string&gt; {\"C\", \"C++\", \"C#\", \"Java\", \"Scala\", \"TypeScript\", \r\n                    \"Python\", \"JavaScript\", \"Rust\", \"Assembly\", \"Pascal\"};\r\n\r\nAssert.IsTrue(_languages.IsSubsetOf(moreLanguages));\r\nAssert.IsTrue(_languages.IsProperSubsetOf(moreLanguages));\r\nAssert.IsTrue(moreLanguages.IsSupersetOf(_languages));\r\nAssert.IsTrue(moreLanguages.IsProperSupersetOf(_languages));<\/pre>\n<p>We create a larger set <code>moreLanguages<\/code> that contains more elements, including all the elements in the <code>languages<\/code> set. Therefore, <code>languages<\/code> is a proper subset of <code>moreLanguages<\/code> , and the latter is the proper superset of the former.\u00a0<\/p>\n<h3><a id=\"union\"><\/a>UnionWith<\/h3>\n<p>When we want to join two sets, we perform a union operation. For example, when we want to perform a union between two sets, A and B, we copy the elements in set B over into set A.\u00a0<\/p>\n<p>Let&#8217;s perform a <code>UnionWith()<\/code> operation between <code>_languages<\/code> and <code>moreLanguages<\/code> HashSet to illustrate this concept:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var moreLanguages = new HashSet&lt;string&gt; { \"Assembly\", \"Pascal\", \"HTML\", \"CSS\", \"PHP\" };\r\n\r\n_languages.UnionWith(moreLanguages);\r\nAssert.AreEqual(_languages.Count(), 14);<\/pre>\n<p>The <code>UnionWith()<\/code> method copies the elements in <code>moreLanguages<\/code> HashSet into the <code>_languages<\/code> HashSet hence, the latter now has fourteen elements instead of nine.\u00a0<\/p>\n<h3><a id=\"intersect\"><\/a>IntersectWith<\/h3>\n<p>An intersection between sets A and B entails finding the common elements. To accomplish such an operation in C#, we use the inbuilt <code>IntersetWith()<\/code> method.\u00a0<\/p>\n<p>Let&#8217;s understand how to perform an intersection operation with an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var moreLanguages = new HashSet&lt;string&gt; { \"C\", \"C++\", \"C#\", \"Java\", \"Scala\", \"Assembly\", \r\n                    \"Pascal\", \"HTML\", \"CSS\", \"PHP\" };\r\n\r\n_languages.IntersectWith(moreLanguages);\r\n\r\nAssert.AreEqual(_languages.Count(), 5);\r\nAssert.IsTrue(_languages.Contains(\"C\"));\r\nAssert.IsTrue(_languages.Contains(\"C++\"));\r\nAssert.IsTrue(_languages.Contains(\"C#\"));\r\nAssert.IsTrue(_languages.Contains(\"Java\"));\r\nAssert.IsTrue(_languages.Contains(\"Scala\"));\r\nAssert.IsFalse(_languages.Contains(\"Assembly\"));<\/pre>\n<p>Here, the <code>IntersectWith()<\/code> method selects the elements that are common in both <code>_languages<\/code> and <code>moreLanguages<\/code> sets.\u00a0<\/p>\n<h3><a id=\"except-with\"><\/a>ExceptWith<\/h3>\n<p>This operation performs a set difference operation between two sets. If we perform a set difference between sets A and B, the operation returns the elements in A that are not present in B.<\/p>\n<p>Let&#8217;s understand this concept with another example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var moreLanguages = new HashSet&lt;string&gt; { \"C\", \"C++\", \"C#\", \"Java\", \"Scala\", \"Assembly\", \r\n                    \"Pascal\", \"HTML\", \"CSS\", \"PHP\" };\r\n\r\n_languages.ExceptWith(moreLanguages);\r\n\r\nAssert.AreEqual(_languages.Count(), 4);\r\nAssert.IsTrue(_languages.Contains(\"TypeScript\"));\r\nAssert.IsTrue(_languages.Contains(\"Python\"));\r\nAssert.IsTrue(_languages.Contains(\"JavaScript\"));\r\nAssert.IsTrue(_languages.Contains(\"Rust\"));\r\nAssert.IsFalse(_languages.Contains(\"Assembly\"));<\/pre>\n<p>The <code>ExceptWith()<\/code> method returns the elements that are in <code>_languages<\/code> but not in <code>moreLanguages<\/code>, which are: &#8220;TypeScript&#8221;, &#8220;Python&#8221;, &#8220;JavaScript&#8221; and &#8220;Rust&#8221;.\u00a0<\/p>\n<h3><a id=\"symmetric-except-with\"><\/a>SymmetricExceptWith<\/h3>\n<p>Sometimes, we may want to modify a HashSet to store unique elements between two sets. That&#8217;s where the <code>SymmetricExceptWith()<\/code> method comes into play, as we can use it to accomplish our purpose.<\/p>\n<p>Let&#8217;s look at using the <code>SymmetricExceptWith()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var moreLanguages = new HashSet&lt;string&gt; { \"Assembly\", \"Pascal\", \"HTML\", \"CSS\", \"PHP\" };\r\n\r\n_languages.SymmetricExceptWith(moreLanguages);\r\n\r\nAssert.AreEqual(_languages.Count(), 14);<\/pre>\n<p>The <code>SymmetricExceptWith()<\/code> method modifies the <code>_languages<\/code> HashSet to make it have unique elements from both itself and <code>moreLanguages<\/code> HashSet. Therefore, since both sets have unique values, the modified <code>_languages<\/code> HashSet now contains fourteen elements.\u00a0<\/p>\n<h2><a id=\"benefits\"><\/a>Benefits of a HashSet in C#<\/h2>\n<p>First, since HashSets use hash tables, they facilitate quick insertion and retrieval operations as <strong>they have a constant access time of O(1).<\/strong><\/p>\n<p>Also, we can use HashSets in applications that <strong>do not allow duplicate elements<\/strong>, which helps us eliminate data redundancy.<\/p>\n<p>Finally, HashSets can be useful for quickly <strong>checking if an element is present in the set without having to iterate<\/strong> through all of the elements.\u00a0<\/p>\n<h2><a id=\"drawbacks\"><\/a>Drawbacks of a HashSet in C#<\/h2>\n<p>One drawback of using a HashSet is that it <strong>does not maintain the order of its elements<\/strong>, so the order in which we iterate over them may vary.<\/p>\n<p>Also, using HashSets may not be suitable for all situations where we need to <strong>store duplicate elements<\/strong>.<\/p>\n<p>The HashSet data structure has limited methods available compared to other data structures such as <a href=\"https:\/\/code-maze.com\/csharp-list-collection\/\" target=\"_blank\" rel=\"noopener\">lists<\/a> or <a href=\"https:\/\/code-maze.com\/dictionary-csharp\/\" target=\"_blank\" rel=\"noopener\">dictionaries<\/a>.\u00a0<\/p>\n<h2><a id=\"conclusion\"><\/a>Conclusion<\/h2>\n<p>In this article, we learn that a HashSet can be a useful solution in C# when inserting and retrieving<strong>\u00a0elements as fast as possible<\/strong>. We can also use HashSets when we want <strong>to store unique elements<\/strong>.<\/p>\n<p>However, it is important to consider our specific needs before deciding on a solution as it may not be suitable for all situations. Additionally, we have to keep in mind that a HashSet <strong>does not maintain the order of its elements<\/strong> and <strong>does not allow for accessing elements by their indices<\/strong>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to take a look at the HashSet class in C#. We will discuss how to use it and its key features. Also, we are going to see some examples of how to use it in practice. Finally, we&#8217;ll compare it to other data structures available in C#. Without further [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[1476,1477],"class_list":["post-76166","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-hashset","tag-hashset-in-c","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>HashSet in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-hashset\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"HashSet in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-hashset\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-11-02T07:00:02+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-11-26T15:38:43+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"HashSet in C#\",\"datePublished\":\"2022-11-02T07:00:02+00:00\",\"dateModified\":\"2022-11-26T15:38:43+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/\"},\"wordCount\":1582,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"hashset\",\"hashset in c#\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-hashset\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/\",\"url\":\"https:\/\/code-maze.com\/csharp-hashset\/\",\"name\":\"HashSet in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-11-02T07:00:02+00:00\",\"dateModified\":\"2022-11-26T15:38:43+00:00\",\"description\":\"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-hashset\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-hashset\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"HashSet in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"HashSet in C# - Code Maze","description":"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-hashset\/","og_locale":"en_US","og_type":"article","og_title":"HashSet in C# - Code Maze","og_description":"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.","og_url":"https:\/\/code-maze.com\/csharp-hashset\/","og_site_name":"Code Maze","article_published_time":"2022-11-02T07:00:02+00:00","article_modified_time":"2022-11-26T15:38:43+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-hashset\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"HashSet in C#","datePublished":"2022-11-02T07:00:02+00:00","dateModified":"2022-11-26T15:38:43+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/"},"wordCount":1582,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["hashset","hashset in c#"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-hashset\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-hashset\/","url":"https:\/\/code-maze.com\/csharp-hashset\/","name":"HashSet in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-11-02T07:00:02+00:00","dateModified":"2022-11-26T15:38:43+00:00","description":"In this article, we are going to look at the HashSet class in C#, along with some of its benefits and drawbacks.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-hashset\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-hashset\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-hashset\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-hashset\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"HashSet in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76166","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=76166"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76166\/revisions"}],"predecessor-version":[{"id":77820,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/76166\/revisions\/77820"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=76166"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=76166"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=76166"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}