.NET 幫助

HashSet C#(開發人員如何使用)

Chipego
奇佩戈·卡林达
2024年3月6日
分享:

介紹

使用 C# 編程具有靈活性,並提供大量資料結構來有效管理各種工作。 HashSet 是一個強大的資料結構,它提供了獨特的元素以及對基本操作的恆定時間平均複雜度。 本文將探討在 C# 中使用 HashSet 以及如何與IronPDF這個強大的 PDF 文檔處理庫一起使用。

如何使用 HashSet C

  1. 建立一個新的主控台應用程式專案。

  2. 在 C# 中建立一個 HashSet 物件。 將預設值添加到HashSet中。

  3. 在添加時,HashSet會自動檢查元素是否存在並移除重複的元素。

  4. 逐一處理 HashSet 中唯一的元素。

  5. 顯示結果並處理物件。

理解 C# 中的 HashSet

C# 中的 HashSet 設計用來提供高效能的集合操作。 HashSet 是在需要保持一組獨特數據時使用的理想集合,因為它防止了重複元素。 它包含在 System.Assortments.Hash tables 中,是 C# 泛型命名空间的基础,并提供快速的插入、删除、更快的检索和查找操作。 我們也可以在 HashSet 元素中找到合適的子集。 在 C# 中,使用 HashSet 集合操作方法可以讓您輕鬆地執行標準集合操作。 HashSet 類別提供集合運算方法。

以下是 HashSet 在 C# 中的一些用途:

初始化與基本操作

建立一個 HashSet 並執行基本操作,如添加、刪除和驗證條目是否存在。

// 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)
$vbLabelText   $csharpLabel

使用集合初始化

使用現有集合作為 HashSet 的起點,重複項會立即被消除。

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)
$vbLabelText   $csharpLabel

與另一個 HashSet 聯合

使用 UnionWith 函數將兩個 HashSet 實例合併,以產生一個新的集合,該集合結合了兩個集合中的不同項目。

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 }
$vbLabelText   $csharpLabel

與另一個 HashSet 的交集

使用 IntersectWith 函數,確定兩個 HashSet 實例之間的共有組件。

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 }
$vbLabelText   $csharpLabel

與另一個 HashSet 的差異

使用 ExceptWith 函數,找到存在於一個 HashSet 但不在另一個中的元素。

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 }
$vbLabelText   $csharpLabel

檢查子集或超集:

使用 IsSubsetOf 和 IsSupersetOf 方法,可以確定給定的 HashSet 實例是否為另一個的子集或超集。

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
$vbLabelText   $csharpLabel

對稱差集

使用 SymmetricExceptWith 技術,確定對稱差異(在一個集合中存在但在兩個集合中都不存在的元素)。

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 }
$vbLabelText   $csharpLabel

IronPDF

程式設計師可以使用 C# 語言,透過利用IronPDF .NET library來製作、編輯和修改 PDF 文件。 該應用程序提供多種工具和功能以實現不同的 PDF 文件操作,包括從 HTML 創建新的 PDF、將 HTML 轉換為 PDF、合併或拆分 PDF 文件以及用文本、照片和其他數據註釋現有 PDF。 欲了解更多有關 IronPDF 的資訊,請參閱官方文件

IronPDF 在HTML 到 PDF轉換中表現優異,確保精確保留原始佈局和樣式。 它非常適合從基於網絡的內容(如報告、發票和文檔)創建PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,輕鬆製作高品質的 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
$vbLabelText   $csharpLabel

IronPDF 的功能

  • HTML 轉 PDF 轉換:任何種類的 HTML 資料,包括文件、URL 和 HTML 程式碼字串,都可以使用 IronPDF 轉換為 PDF 文件。
  • PDF 生成:可以使用 C# 程式語言將文本、圖片和其他物件以程式方式加入 PDF 文件中。
  • PDF 操作:IronPDF 可以將 PDF 檔案分割成多個檔案,並編輯現有的 PDF 檔案。 它可以將多個 PDF 文件合併為一個文件。
  • PDF表單:因為該程式庫允許使用者建立和填寫PDF表單,因此在需要收集和處理表單數據的情境中非常有用。
  • 安全功能:IronPDF 允許進行 PDF 文件加密以及使用密碼和權限安全措施。

安裝 IronPDF

獲取IronPDF庫; 即將到來的補丁需要它。 要做到這一點,請在套件管理器中輸入以下代碼:

Install-Package IronPDF 
//or 
dotnet add package IronPdf

HashSet C#(開發人員如何運作):圖1 - 使用套件管理器主控台安裝IronPDF庫,並輸入以下命令:「Install-Package IronPDF」或「dotnet add package IronPdf」。

另一個選擇是使用 NuGet 套件管理器查找「IronPDF」套件。 從所有與 IronPDF 相關的 NuGet 套件中,我們可以從此列表中選擇並下載所需的套件。

![HashSet C#(開發人員如何運作):圖2 - 您可以使用NuGet套件管理器安裝IronPDF庫。 在「瀏覽」標籤中搜索包「ironpdf」,然後選擇並安裝最新版本的IronPDF。

使用 IronPDF 的 HashSet

在 C# 環境中,IronPDF 是一個強大的庫,使處理 PDF 文件更加容易。 在數據表現和有效文件創建至關重要的情況下,結合 HashSet 的效率與 IronPDF 的文件操作能力可能會帶來創新的解決方案。

使用 HashSet 與 IronPDF 的好處

  • 資料冗餘減少:通過確保僅保留不重複的元素,HashSets 有助於避免資料重複。 在處理大量數據集以刪除重複信息時,這非常有用。
  • 有效查找:使用 HashSet 時,基本操作如插入、刪除和查找可以在平均常數時間複雜度下執行。 在處理不同大小的數據集時,這種性能非常重要。
  • 簡化文件製作:IronPDF 優化了 C# PDF 文件的創建過程。 通過將 HashSet 與 IronPDF 集成,您可以建立快速且有效的流程來生成原創且動態的 PDF 內容。

    現在讓我們看看在實際情境中使用 HashSet 與 IronPDF 可能有用的情況。

生成具有獨特數據的PDF

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
$vbLabelText   $csharpLabel

在上述代碼範例中,我們使用 HashSet uniqueUserNames 儲存從陣列中獲取的唯一使用者名稱。 HashSet 自動消除重複項。 接下來,我們使用 IronPDF 在 PDF 文件中創建這些不同用戶名稱的無序列表。 欲了解更多有關程式碼的資訊,請查看使用 HTML 創建 PDF

輸出

HashSet C#(它如何為開發者工作):圖 3 - 輸出:UniqueUserNames.pdf

結論

總結來說,C# 的 HashSet 資料結構是一種有效的工具,用於組織不同項目的集合。 當與 IronPDF 結合使用時,它為動態、獨一無二以及性能優化的 PDF 文件創建提供了新的機會。

我們在給出的範例中說明了如何使用 HashSet 來保證資料的唯一性,同時使用 IronPDF 來創建 PDF 文件。 建立強大且有效的 C# 應用程式可以從 HashSet 和 IronPDF 的組合中受益,無論您是從事資料去重、報告還是管理動態內容。 在深入研究時,請考慮在多種情境下利用此組合來改善應用程式的易用性和功能性。

IronPDF 的 $749 Lite 版本附帶永久授權、升級選項和一年的軟體支援。 在水印試用期內了解更多有關IronPDF的價格、授權和免費試用的信息。 請訪問 Iron Software 網站,以獲取更多關於Iron Software的資訊。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# Nameof(它如何為開發者工作)
下一個 >
C# 陣列長度(開發人員如何使用)