.NET 幫助

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

發佈 2024年3月6日
分享:

簡介

使用C#編程具有靈活性,並提供大量的數據結構來有效地管理各種任務。 HashSet 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類提供了集合操作方法。

以下是一些C#中使用HashSet的例子:

初始化與基本操作

建立 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)
VB   C#

使用集合初始化

使用現有的集合作為 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)
VB   C#

與另一個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 }
VB   C#

與另一個 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 }
VB   C#

與另一個 HashSet 的區別

使用 ExceptWith 函數,查找在一個 HashSet 中但不在另一個 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 }
VB   C#

檢查子集或超集:

使用 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
VB   C#

對稱差異

使用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 }
VB   C#

IronPDF

程序員可以利用C#語言來生成、編輯和修改PDF文件,通過使用IronPDF。 IronPDF .NET PDF 庫。該應用程序提供了廣泛的工具和特性,能夠對PDF文件進行各種操作,包括從HTML創建新的PDF、將HTML轉換為PDF、合併或拆分PDF文檔,以及用文本、照片和其他數據註釋現有PDF。要了解更多有關IronPDF的信息,請參考這個 文檔.

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。

HashSet與IronPDF

在C#環境中,IronPDF是一個可以讓處理PDF文件變得更簡單的強大庫。在需要區分數據表示和有效文件創建的情況下,將HashSet的效率與IronPDF的文件操作功能結合起來,可能會得到創造性的解決方案。

使用 HashSet 與 IronPDF 的好處

  • 減少數據冗餘:透過確保僅保留獨特的元素,HashSet 有助於避免數據重複。當處理大規模數據集以移除重複信息時,這非常有幫助。
  • 高效查找:利用 HashSet 可以以恆定時間平均複雜度執行插入、刪除和查找等基本操作。這種性能在處理不同規模數據集時非常重要。
  • 簡化文件生成:IronPDF 簡化了 C# PDF 文件的創建過程。通過將 HashSet 與 IronPDF 集成,您可以快速高效地建立生成原始和動態內容的流程。

現在讓我們看看一個使用 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
VB   C#

在上述程式碼範例中,我們使用 HashSet uniqueUserNames 保存從陣列中檢索到的唯一用戶名。HashSet 自動消除重複項。接下來,我們使用 IronPDF 在 PDF 文件中創建這些不同用戶名的無序列表。欲了解更多關於此程式碼的信息,請查看 這裡.

輸出

HashSet C#(開發者如何使用):圖 3 - 輸出:UniqueUserNames.pdf

結論

總而言之,C# HashSet 資料結構是一個有效的工具,用於組織不同項目的集合。當與 IronPDF 搭配使用時,它為動態、獨特且性能優化的 PDF 文件創建創造了新的機會。

我們說明了如何使用 HashSet 來保證數據的唯一性,同時使用 IronPDF 在給定的範例中創建PDF文件。建立強大和高效的C#應用程式可能會從HashSet和IronPDF的組合中受益,無論您是在处理數據去重、報告還是管理動態內容。隨著您進一步研究,請考慮您可能在多个背景下使用這種組合來提高您的應用程式的可用性和功能。

IronPDF的$liteLicense Lite版本隨附永久許可證、升級選項和一年的軟體支援。整個水印 試用期 了解有關IronPDF的價格、授權和免費試用的更多信息。請訪問此 頁面 有關 Iron Software 的更多資訊。

< 上一頁
C# Nameof(它如何為開發者工作)
下一個 >
C# 陣列長度(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >