Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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.Collections.Generic namespace and provides quick insertion, deletion, faster retrieval, and lookup operations. 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:
Establishing a HashSet and carrying out fundamental actions such as appending, deleting, and verifying the existence of entries.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Initializes a HashSet of integers
HashSet<int> numbers = new HashSet<int>();
// Adds elements to the HashSet
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Removes an element from the HashSet
numbers.Remove(2);
// Checks for membership of an element
bool containsThree = numbers.Contains(3);
Console.WriteLine($"Contains 3: {containsThree}");
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Initializes a HashSet of integers
HashSet<int> numbers = new HashSet<int>();
// Adds elements to the HashSet
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Removes an element from the HashSet
numbers.Remove(2);
// Checks for membership of an element
bool containsThree = numbers.Contains(3);
Console.WriteLine($"Contains 3: {containsThree}");
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
' Initializes a HashSet of integers
Dim numbers As New HashSet(Of Integer)()
' Adds elements to the HashSet
numbers.Add(1)
numbers.Add(2)
numbers.Add(3)
' Removes an element from the HashSet
numbers.Remove(2)
' Checks for membership of an element
Dim containsThree As Boolean = numbers.Contains(3)
Console.WriteLine($"Contains 3: {containsThree}")
End Sub
End Class
Using an existing collection as the starting point for a HashSet, duplicates are immediately eliminated.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creates a list with duplicate elements
List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 };
// Initializes a HashSet with the list, automatically removes duplicates
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
Console.WriteLine("Unique numbers:");
foreach (var number in uniqueNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creates a list with duplicate elements
List<int> duplicateNumbers = new List<int> { 1, 2, 2, 3, 3, 4 };
// Initializes a HashSet with the list, automatically removes duplicates
HashSet<int> uniqueNumbers = new HashSet<int>(duplicateNumbers);
Console.WriteLine("Unique numbers:");
foreach (var number in uniqueNumbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
' Creates a list with duplicate elements
Dim duplicateNumbers As New List(Of Integer) From {1, 2, 2, 3, 3, 4}
' Initializes a HashSet with the list, automatically removes duplicates
Dim uniqueNumbers As New HashSet(Of Integer)(duplicateNumbers)
Console.WriteLine("Unique numbers:")
For Each number In uniqueNumbers
Console.WriteLine(number)
Next number
End Sub
End Class
Combining two HashSet instances to produce a new set that combines distinct items from both sets using the UnionWith function.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Merges set2 into set1
set1.UnionWith(set2);
Console.WriteLine("Union of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Merges set2 into set1
set1.UnionWith(set2);
Console.WriteLine("Union of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
' Merges set2 into set1
set1.UnionWith(set2)
Console.WriteLine("Union of set1 and set2:")
For Each item In set1
Console.WriteLine(item)
Next item
End Sub
End Class
Using the IntersectWith function, determine the shared components between two HashSet instances.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Keeps only elements that are present in both sets
set1.IntersectWith(set2);
Console.WriteLine("Intersection of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Keeps only elements that are present in both sets
set1.IntersectWith(set2);
Console.WriteLine("Intersection of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
' Keeps only elements that are present in both sets
set1.IntersectWith(set2)
Console.WriteLine("Intersection of set1 and set2:")
For Each item In set1
Console.WriteLine(item)
Next item
End Sub
End Class
Using the ExceptWith function, find the elements that are in one HashSet but not in another.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Removes elements from set1 that are also in set2
set1.ExceptWith(set2);
Console.WriteLine("Difference of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Removes elements from set1 that are also in set2
set1.ExceptWith(set2);
Console.WriteLine("Difference of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
' Removes elements from set1 that are also in set2
set1.ExceptWith(set2)
Console.WriteLine("Difference of set1 and set2:")
For Each item In set1
Console.WriteLine(item)
Next item
End Sub
End Class
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.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
// Checks if set2 is a subset of set1
bool isSubset = set2.IsSubsetOf(set1);
// Checks if set1 is a superset of set2
bool isSuperset = set1.IsSupersetOf(set2);
Console.WriteLine($"Is set2 a subset of set1: {isSubset}");
Console.WriteLine($"Is set1 a superset of set2: {isSuperset}");
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 2, 3 };
// Checks if set2 is a subset of set1
bool isSubset = set2.IsSubsetOf(set1);
// Checks if set1 is a superset of set2
bool isSuperset = set1.IsSupersetOf(set2);
Console.WriteLine($"Is set2 a subset of set1: {isSubset}");
Console.WriteLine($"Is set1 a superset of set2: {isSuperset}");
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {2, 3}
' Checks if set2 is a subset of set1
Dim isSubset As Boolean = set2.IsSubsetOf(set1)
' Checks if set1 is a superset of set2
Dim isSuperset As Boolean = set1.IsSupersetOf(set2)
Console.WriteLine($"Is set2 a subset of set1: {isSubset}")
Console.WriteLine($"Is set1 a superset of set2: {isSuperset}")
End Sub
End Class
Using the SymmetricExceptWith technique, determine the symmetric difference (elements present in one set, but not in both).
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Keeps elements that are in set1 or set2 but not in both
set1.SymmetricExceptWith(set2);
Console.WriteLine("Symmetric difference of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };
// Keeps elements that are in set1 or set2 but not in both
set1.SymmetricExceptWith(set2);
Console.WriteLine("Symmetric difference of set1 and set2:");
foreach (var item in set1)
{
Console.WriteLine(item);
}
}
}
Imports System
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim set1 As New HashSet(Of Integer) From {1, 2, 3}
Dim set2 As New HashSet(Of Integer) From {3, 4, 5}
' Keeps elements that are in set1 or set2 but not in both
set1.SymmetricExceptWith(set2)
Console.WriteLine("Symmetric difference of set1 and set2:")
For Each item In set1
Console.WriteLine(item)
Next item
End Sub
End Class
Programmers may use the C# language to produce, edit, and modify PDF documents by utilizing the IronPDF .NET 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 the official documentation.
IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
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
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.
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.
Now let's look at a real-world scenario where using HashSet with IronPDF might be useful.
using IronPdf;
using System;
using System.Collections.Generic;
class PdfGenerator
{
static void Main()
{
// Sample user names with duplicates
string[] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
// Using HashSet to ensure 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
HtmlToPdf renderer = new HtmlToPdf();
// Render a PDF from an HTML document consisting of unique user names
var 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;
class PdfGenerator
{
static void Main()
{
// Sample user names with duplicates
string[] userNames = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" };
// Using HashSet to ensure 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
HtmlToPdf renderer = new HtmlToPdf();
// Render a PDF from an HTML document consisting of unique user names
var 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
Friend Class PdfGenerator
Shared Sub Main()
' Sample user names with duplicates
Dim userNames() As String = { "Alice", "Bob", "Charlie", "Bob", "David", "Alice" }
' Using HashSet to ensure 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 HtmlToPdf()
' Render a PDF from an HTML document consisting of unique user names
Dim pdf = 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
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 using HTML to create a PDF.
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 on licensing to find out more about IronPDF's price, licensing, and free trial. Visit the Iron Software website for further information on Iron Software.
HashSet in C# is a collection designed to contain unique elements and provides high-performance set operations with constant-time average complexity for basic operations. It is part of the System.Collections.Generic namespace.
You can initialize a HashSet in C# using the HashSet constructor, optionally passing in an existing collection to eliminate duplicates. For example: HashSet
HashSet is used to ensure data uniqueness by automatically eliminating duplicates, which is useful when generating documents or reports to maintain distinct elements.
Basic operations with a HashSet include adding elements, removing elements, and checking for the existence of elements. These operations offer efficient performance due to the underlying hash table implementation.
HTML content, including HTML strings, files, and URLs, can be converted into PDF documents while preserving the original layouts and styles, making it suitable for creating PDFs from web-based content like reports and invoices.
HashSet provides methods for set operations such as UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, IsSubsetOf, and IsSupersetOf, allowing for union, intersection, difference, symmetric difference, and subset/superset checks.
Using HashSet helps in reducing data redundancy by ensuring unique elements and provides efficient lookup operations. This aids in simplifying dynamic and performance-optimized data processing tasks.
You can install a library in a C# project using the NuGet Package Manager with the command: Install-Package
Yes, you can combine two HashSets using the UnionWith method, which merges the elements of the second HashSet into the first, ensuring only unique elements are retained.
The purpose of using a HashSet in document generation is to manage unique data efficiently, ensuring that the content added is distinct, which is particularly useful for dynamic content creation and reporting.