.NET HELP

HashSet C# (How It Works For Developers)

Published March 6, 2024
Share:

Introduction

Programming in C# is flexible and provides a large array of data structures to effectively manage various jobs. The HashSet is one such potent data structure that offers distinct components and constant-time average complexity for fundamental operations. This post will examine the use of HashSet in C# and how it may be used with IronPDF, a powerful library for working with PDF documents.

How to use HashSet C#

  1. Create a new Console App project.
  2. Create an object for the HashSet in C#. Add the default value to the HashSet.
  3. While adding, HashSet will automatically remove duplicate elements by checking if the element exists.
  4. Process the HashSet only unique elements one by one.
  5. Display the result and dispose of the object.

Understanding HashSet in C#

HashSet in C# is designed to provide high-performance set operations. A HashSet is the perfect collection to use in situations when you need to keep a distinct set of data since it prevents duplicate elements. It's included in the System.Assortments.Hash tables, the foundation of the C# generic namespace, and provides quick insertion, deletion, faster retrieval and lookup operations. We can also find the proper subset in the HashSet elements. In C#, use HashSet set operations methods that let you easily carry out standard set operations. The HashSet class provides set operations methods.

The following are a few C# uses for a HashSet:

Initialization and Basic Operations

Establishing a HashSet and carrying out fundamental actions such as appending, deleting, and verifying the existence of entries.

// set operations 
HashSet<int> numbers = new HashSet<int>();
// Add elements
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Remove an element, predicate function
numbers.Remove(2);
// Check for membership or duplicate element
bool containsThree = numbers.Contains(3);
// set operations 
HashSet<int> numbers = new HashSet<int>();
// Add elements
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Remove an element, predicate function
numbers.Remove(2);
// Check for membership or duplicate element
bool containsThree = numbers.Contains(3);
' set operations 
Dim numbers As New HashSet(Of Integer)()
' Add elements
numbers.Add(1)
numbers.Add(2)
numbers.Add(3)
' Remove an element, predicate function
numbers.Remove(2)
' Check for membership or duplicate element
Dim containsThree As Boolean = numbers.Contains(3)
VB   C#

Initialization with Collection

Using an existing collection as the starting point for a HashSet, duplicates are immediately eliminated.

List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 }; // all the elements
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 }; // all the elements
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
Dim duplicateNumbers As New List(Of Integer) From {1, 2, 2, 3, 3, 4} ' all the elements
Dim uniqueNumbers As New HashSet(Of Integer)(duplicateNumbers)
VB   C#

Union with Another HashSet

Combining two HashSet instances to produce a new set that combines distinct items from both sets using the UnionWith function.

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 now contains { 1, 2, 3, 4, 5 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.UnionWith(set2); // set1 now contains { 1, 2, 3, 4, 5 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.UnionWith(set2) ' set1 now contains { 1, 2, 3, 4, 5 }
VB   C#

Intersection with Another HashSet

Using the IntersectWith function, determine the shared components between two HashSet instances.

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.IntersectWith(set2); // set1 now contains { 3 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.IntersectWith(set2); // set1 now contains { 3 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.IntersectWith(set2) ' set1 now contains { 3 }
VB   C#

Difference with Another HashSet

Using the ExceptWith function, find the elements that are in one HashSet but not in another.

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.ExceptWith(set2); // set1 now contains { 1, 2 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.ExceptWith(set2); // set1 now contains { 1, 2 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.ExceptWith(set2) ' set1 now contains { 1, 2 }
VB   C#

Checking for Subset or Superset:

Using the IsSubsetOf and IsSupersetOf methods, one may ascertain whether a given HashSet instance is a subset or superset of another.

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
bool isSubset = set2.IsSubsetOf(set1); // returns true
bool isSuperset = set1.IsSupersetOf(set2); // returns true
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
bool isSubset = set2.IsSubsetOf(set1); // returns true
bool isSuperset = set1.IsSupersetOf(set2); // returns true
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {2, 3}
Dim isSubset As Boolean = set2.IsSubsetOf(set1) ' returns true
Dim isSuperset As Boolean = set1.IsSupersetOf(set2) ' returns true
VB   C#

Symmetric Difference

Using the SymmetricExceptWith technique, determine the symmetric difference (elements present in one set, but not in both).

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.SymmetricExceptWith(set2); // set1 now contains { 1, 2, 4, 5 }
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
set1.SymmetricExceptWith(set2); // set1 now contains { 1, 2, 4, 5 }
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
set1.SymmetricExceptWith(set2) ' set1 now contains { 1, 2, 4, 5 }
VB   C#

IronPDF

Programmers may use the C# language to produce, edit, and modify PDF documents by utilizing the IronPDF .NET PDF library. The application offers a wide range of tools and features to enable different operations with PDF files, including creating new PDFs from HTML, converting HTML to PDF, combining or dividing PDF documents, and annotating existing PDFs with text, photos, and other data. To know more about the IronPDF, refer to this documentation.

Features of IronPDF

  • HTML to PDF conversion: Any kind of HTML data, including files, URLs, and HTML code strings, may be converted into PDF documents with IronPDF.
  • PDF Generation: Text, images, and other objects may be programmatically added to PDF documents using the C# programming language.
  • PDF Manipulation: IronPDF can divide a PDF file into numerous files and edit pre-existing PDF files. It can merge several PDF files into a single file.
  • PDF Forms: Because the library enables users to build and complete PDF forms, it is useful in scenarios where form data needs to be gathered and processed.
  • Security Features: IronPDF allows for PDF document encryption as well as password and permission security.

Install IronPDF

Acquire the IronPDF library; the upcoming patch requires it. To do this, enter the following code into the Package Manager:

Install-Package IronPDF 
//or 
dotnet add package IronPdf

HashSet C# (How It Works For Developers): Figure 1 - Install IronPDF library using Package Manager Console and entering the following commands: "Install-Package IronPDF" or "dotnet add package IronPdf".

Another option is to look for the package "IronPDF" using the NuGet Package Manager. From all the NuGet packages related to IronPDF, we may select and download the required package from this list.

HashSet C# (How It Works For Developers): Figure 2 - You can install IronPDF library using NuGet Package Manager. Search for the package "ironpdf" in the Browse tab, then select and install the latest version of the IronPDF.

HashSet with IronPDF

Within the C# environment, IronPDF is a powerful library that makes working with PDF documents easier. In situations where distinct data representation and effective document creation are crucial, combining the efficiency of HashSet with the document manipulation powers of IronPDF might result in creative solutions.

Benefits of Using HashSet with IronPDF

  • Data Redundancy Reduction: By ensuring that only distinct elements are kept, HashSets help to avoid data duplication. When dealing with huge datasets to remove duplicate information, this is quite helpful.
  • Effective Lookup: Basic operations such as insertion, deletion, and lookup may be performed with constant-time average complexity using HashSet. This kind of performance is very important when working with different-sized datasets.
  • Simplified Production of Documents: IronPDF streamlines the C# PDF document creation process. You may establish fast and effective processes for producing original and dynamic content for your PDFs by integrating HashSet with IronPDF.

Now let's look at a real-world scenario where using HashSet with IronPDF might be useful.

Generating PDF with Unique Data

using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
class PdfGenerator
{
    static void Main()
    {
        // Sample user names
        string [] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
        // Using HashSet to store unique user names
        HashSet<string> uniqueUserNames = new HashSet<string>(userNames);
        // Generating PDF with unique user names
        GeneratePdf(uniqueUserNames);
    }
    static void GeneratePdf(HashSet<string> uniqueUserNames)
    {
        // Create a new PDF document using IronPDF
        IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
        PdfDocument pdf = renderer.RenderHtmlAsPdf(BuildHtmlDocument(uniqueUserNames));
        // Save the PDF to a file
        string pdfFilePath = "UniqueUserNames.pdf";
        pdf.SaveAs(pdfFilePath);
        // Display a message with the file path
        Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}");
    }
    static string BuildHtmlDocument(HashSet<string> uniqueUserNames)
    {
        // Build an HTML document with unique user names
        string htmlDocument = "<html><body><ul>";
        foreach (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
class PdfGenerator
{
    static void Main()
    {
        // Sample user names
        string [] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
        // Using HashSet to store unique user names
        HashSet<string> uniqueUserNames = new HashSet<string>(userNames);
        // Generating PDF with unique user names
        GeneratePdf(uniqueUserNames);
    }
    static void GeneratePdf(HashSet<string> uniqueUserNames)
    {
        // Create a new PDF document using IronPDF
        IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
        PdfDocument pdf = renderer.RenderHtmlAsPdf(BuildHtmlDocument(uniqueUserNames));
        // Save the PDF to a file
        string pdfFilePath = "UniqueUserNames.pdf";
        pdf.SaveAs(pdfFilePath);
        // Display a message with the file path
        Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}");
    }
    static string BuildHtmlDocument(HashSet<string> uniqueUserNames)
    {
        // Build an HTML document with unique user names
        string htmlDocument = "<html><body><ul>";
        foreach (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Friend Class PdfGenerator
	Shared Sub Main()
		' Sample user names
		Dim userNames() As String = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" }
		' Using HashSet to store unique user names
		Dim uniqueUserNames As New HashSet(Of String)(userNames)
		' Generating PDF with unique user names
		GeneratePdf(uniqueUserNames)
	End Sub
	Private Shared Sub GeneratePdf(ByVal uniqueUserNames As HashSet(Of String))
		' Create a new PDF document using IronPDF
		Dim renderer As New IronPdf.HtmlToPdf()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(BuildHtmlDocument(uniqueUserNames))
		' Save the PDF to a file
		Dim pdfFilePath As String = "UniqueUserNames.pdf"
		pdf.SaveAs(pdfFilePath)
		' Display a message with the file path
		Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}")
	End Sub
	Private Shared Function BuildHtmlDocument(ByVal uniqueUserNames As HashSet(Of String)) As String
		' Build an HTML document with unique user names
		Dim htmlDocument As String = "<html><body><ul>"
		For Each userName In uniqueUserNames
			htmlDocument &= $"<li>{userName}</li>"
		Next userName
		htmlDocument &= "</ul></body></html>"
		Return htmlDocument
	End Function
End Class
VB   C#

In the above code example, we save unique user names retrieved from an array using a HashSet uniqueUserNames. The HashSet automatically eliminates duplicates. Next, we create an unordered list of these distinct user names in a PDF document using IronPDF. To know more about the code check here.

OUTPUT

HashSet C# (How It Works For Developers): Figure 3 - Output: UniqueUserNames.pdf

Conclusion

To sum up, the C# HashSet data structure is an effective tool for organizing sets of distinct items. It creates new opportunities for dynamic, one-of-a-kind, and performance-optimized PDF document creation when paired with IronPDF.

We illustrated how to use HashSet to guarantee data uniqueness while using IronPDF to create PDF documents in the example that was given. Building strong and effective C# applications may benefit from the combination of HashSet and IronPDF, whether you're working on data deduplication, reporting, or managing dynamic content. As you investigate more, take into account the many contexts in which you might utilize this combination to improve the usability and functionality of your apps.

The $749 Lite version of IronPDF comes with a permanent license, upgrade options, and a year of software support. Throughout the watermarked trial period to find out more about IronPDF's price, licensing, and free trial. Visit this page for further information on Iron Software.

< PREVIOUS
C# Nameof (How It Works For Developers)
NEXT >
C# Array Length (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,173,334 View Licenses >