HashSet C#(對於開發者的運行原理)
在C#中程式設計柔軟且提供大量資料結構以有效管理各種工作。 HashSet是這樣一種強大的資料結構,提供獨特的元件和基本操作的常數時間平均複雜度。 本文將探討在C#中使用HashSet的方法,以及如何將其與IronPDF結合使用,此庫為處理PDF文件提供了強大的功能。
如何在C#中使用HashSet
- 建立一個新的Console App專案。
- 在C#中為HashSet建立一個物件。 將預設值加入到HashSet中。
- 在新增時,HashSet將自動通過檢查元素是否存在來移除重複的元素。
- 處理HashSet中只有唯一的元素,一個接一個。
- 顯示結果並銷毀物件。
理解C#中的HashSet
C#中的HashSet旨在提供高效能的集合操作。 HashSet是在需要保持資料獨立的情況下使用的完美集合,因為它防止重複元素。 它包含在System.Collections.Generic命名空間中,提供快速的插入、刪除、更快的檢索和查找操作。 在C#中,使用HashSet集合操作方法可讓您輕鬆執行標準集合操作。 HashSet類提供集合操作方法。
以下是HashSet在C#中的一些用法:
初始化和基本操作
建立一個HashSet並執行一些基本動作,如附加、刪除和確認條目的存在。
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
使用集合初始化
使用現有集合作為HashSet的起點,重複項目將立即被消除。
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
與另一個HashSet聯合
結合兩個HashSet實例,以生成一個新集合,使用UnionWith函式結合兩個集合中不同的項目。
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
與另一個HashSet取交集
使用IntersectWith函式來確定兩個HashSet實例之間的共同元件。
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
與另一個HashSet找差異
使用ExceptWith函式尋找在一個HashSet中但不在另一個中的元素。
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
檢查子集或超集:
使用IsSubsetOf和IsSupersetOf方法來確定給定的HashSet實例是否是另一個的子集或超集。
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
對稱差集
使用SymmetricExceptWith技術來確定對稱差集(存在於一個集合中,但不在兩者中)。
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
IronPDF
程式設計師可以使用C#語言通過IronPDF .NET庫來產生、編輯和修改PDF文件。 該應用程式提供了廣泛的工具和功能,以實現與PDF檔案相關的不同操作,包括從HTML建立新的PDF、將HTML轉換為PDF、合併或分割PDF檔案,以及用文字、照片和其他資料對現有的PDF進行註解。 如需了解更多關於IronPDF的資訊,請參閱官方文件。
IronPDF在HTML到PDF的轉換中表現出色,確保精確保留原始佈局和樣式。 它非常適合從基於網路的內容(如報告、發票和文件)建立PDF文件。 用於HTML文件、URL和原始HTML字串的支持,IronPDF可以輕鬆生成高品質的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");
}
}
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
IronPDF的功能
- HTML轉PDF:任何型別的HTML資料,包括檔案、網址和HTML程式碼字串,都可以使用IronPDF轉換為PDF檔案。
- PDF產生:可以使用C#程式語言程式化地將文字、圖像和其他物件加入到PDF文件中。
- PDF操作:IronPDF可以將一個PDF文件分割成多個檔案,並且可以編輯已存在的PDF文件。 它可以將多個PDF檔案合併成一個檔案。
- PDF表單:因為該庫允許使用者建立和填寫PDF表單,在需要收集和處理表單資料的情況下非常有用。
- 安全功能:IronPDF允許對PDF文件進行加密以及密碼和權限的安全設置。
安裝IronPDF
獲取IronPDF程式庫; 即將發布的補丁需要它。 為此,請輸入以下程式碼到Package Manager中:
Install-Package IronPdf
or
dotnet add package IronPdf

另一個選擇是使用NuGet套件管理器搜尋套件"IronPDF"。 從所有與IronPDF相關的NuGet套件中,我們可以從此列表中選擇並下載所需的套件。
! 
HashSet與IronPDF
在C#環境中,IronPDF是一個強大的程式庫,使得處理PDF文件更加簡便。 在獨特資料表示和有效文件建立至關重要的情況下,將HashSet的效率與IronPDF的文件操作功能相結合可能會產生創新解決方案。
使用HashSet與IronPDF的好處
- 降低資料冗餘:通過確保只保留唯一的元素,HashSet有助於避免資料重複。 當處理大型資料集以去除重複資訊時,這非常有幫助。
- 查找效能:使用HashSet可以在常數時間平均複雜度下執行基本操作,如插入、刪除和查找。 當處理不同大小的資料集時,這種效能非常重要。
- 簡化文件生產:IronPDF簡化了C# PDF文件的建立過程。 通過將HashSet與IronPDF結合,您可以快速有效地建立過程以產生您的PDF的原創和動態內容。
現在讓我們看看一個使用HashSet與IronPDF可能有用的實例。
生成擁有唯一資料的PDF
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
在上述程式碼範例中,我們使用HashSet uniqueUserNames保存從陣列中檢索的唯一使用者名。 HashSet自動消除重複項目。 接下來,我們在PDF文件中使用IronPDF建立這些獨特使用者名的無序列表。 要了解有關程式碼的更多資訊,請查看使用HTML建立PDF。
輸出

結論
總結來說,C#中的HashSet資料結構是一種有效的工具,用於組織一組獨特的物件。 當與IronPDF結合使用時,它在動態、獨特和效能優化的PDF文件建立中創造了新的機會。
我們展示了如何使用HashSet來保證資料獨特性,並使用IronPDF來建立PDF文件。 無論您是執行資料去重、報告還是動態內容管理,HashSet和IronPDF的結合都可以為深入和強大的C#應用提供幫助。 當您進一步探索時,請考慮在各種上下文中如何利用這種結合來提高您的應用程式的可用性和功能。
$999 IronPDF的Lite版本附帶永久授權、升級選項和一年的軟體支援。 在帶水印的試用許可期間,有關IronPDF的價格、許可和免費試用的更多資訊。 存取Iron Software網站了解Iron Software的更多資訊。
常見問題
我如何確保在C#中生成PDF文件時的資料唯一性?
您可以使用HashSet來儲存唯一的資料元素,例如使用者名,這樣可以在生成PDF文件之前確保刪除重複項,提供更乾淨和更準確的PDF內容。
在與IronPDF結合使用中,使用HashSet有什麼好處?
將HashSet與IronPDF結合使用可以在建立PDF時有效管理唯一資料。HashSet確保資料唯一性,而IronPDF在將HTML內容轉換為PDF時保持佈局和樣式。
您如何在C#中將HTML內容轉換為PDF?
您可以使用IronPDF的RenderHtmlAsPdf方法在C#中將HTML內容轉換為PDF。此方法允許您直接將HTML字串轉換為PDF,保持原始佈局和樣式。
在C#中,HashSet支持哪些操作?
C#中的HashSet支持一系列集合操作,如UnionWith、IntersectWith、ExceptWith和SymmetricExceptWith,這些操作有助於高效的資料操作和集合比較。
我如何將HashSet與PDF文件建立結合?
要將HashSet與PDF文件建立結合使用,請在傳遞給IronPDF生成最終PDF文件之前,使用HashSet管理和過濾您的資料以確保唯一性。
HashSet在動態內容管理中的角色是什麼?
在動態內容管理中,HashSet通過確保資料唯一性發揮著至關重要的作用,這對於文件生成、報告編制和資料完整性管理等任務至關重要。
您如何在C#項目中安裝IronPDF?
您可以使用NuGet Package Manager的Install-Package IronPdf命令在C#項目中安裝IronPDF,或使用.NET CLI的dotnet add package IronPdf。
HashSet能改善C#應用程式的性能嗎?
是的,HashSet可顯著提高C#應用程式的性能,因為其基本操作如插入、刪除和查找具有恆定時間複雜度,使其在管理大型資料集時效率很高。




