跳過到頁腳內容
.NET幫助

HashSet C#(對於開發者的運行原理)

C# 程式設計非常靈活,並提供大量資料結構以有效管理各種工作。 HashSet 就是這樣一個強大的資料結構,它提供了獨特的元件和基本操作的常時平均複雜度。 本文章將檢視 C# 中 HashSet 的使用,以及如何將其與 IronPDF(一個用於處理 PDF 文件的功能強大的庫)搭配使用。

如何在 C# 中使用 HashSet。

1.建立新的 Console App 專案。 2.在 C# 中為 HashSet 建立物件。 將預設值加入 HashSet。 3.在新增時,HashSet 會透過檢查元素是否存在,自動移除重複的元素。 4.逐一處理 HashSet 中唯一的元素。 5.顯示結果並處理物件。

了解 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 f或 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 f或 membership of an element
        bool containsThree = numbers.Contains(3);

        Console.WriteLine($"Contains 3: {containsThree}");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

使用集合進行初始化

使用現有的集合作為 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:");
        f或each (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:");
        f或each (var number in uniqueNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

與另一個 HashSet 結合

使用 UnionWith 函式結合兩個 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 };

        // Merges set2 into set1
        set1.UnionWith(set2);

        Console.WriteLine("Union of set1 and set2:");
        f或each (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:");
        f或each (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

與另一個 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:");
        f或each (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:");
        f或each (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

與其他 HashSet 的差異

使用 ExceptWith 函式,找出在一個 HashSet 中但不在另一個 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:");
        f或each (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:");
        f或each (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

檢查子集或超集:

使用 IsSubsetOf 和 IsSupersetOf 方法,可以確定指定的 HashSet 範例是另一個 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
$vbLabelText   $csharpLabel

對稱差異

使用 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 或 set2 but not in both
        set1.SymmetricExceptWith(set2);

        Console.WriteLine("Symmetric difference of set1 and set2:");
        f或each (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 或 set2 but not in both
        set1.SymmetricExceptWith(set2);

        Console.WriteLine("Symmetric difference of set1 and set2:");
        f或each (var item in set1)
        {
            Console.WriteLine(item);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronPDF。

程式設計師可以使用 C# 語言,透過 IronPDF f或 .NET 函式庫來製作、編輯和修改 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 函式庫; 即將推出的修補程式需要。 為此,請在套件管理員 (Package Manager) 中輸入下列程式碼:

Install-Package IronPdf

dotnet add package IronPdf

!HashSet C# (How It W或ks F或 Developers):圖 1 - 使用套件管理員控制台安裝 IronPDF 函式庫,並輸入下列指令:"Install-Package IronPDF" 或 "dotnet add package IronPdf"。

另一個選擇是使用 NuGet Package Manager 尋找套件"IronPDF"。 從所有與 IronPDF 相關的 NuGet 套件中,我們可以從此清單中選擇並下載所需的套件。

HashSet C# (How It W或ks F或 Developers):圖 2 - 您可以使用 NuGet Package Manager 安裝 IronPDF 函式庫。 在瀏覽標籤中搜尋套件ironpdf,然後選擇並安裝最新版本的 IronPDF。

HashSet 與 IronPDF

在 C# 環境中,IronPDF 是一個功能強大的函式庫,可讓 PDF 文件的處理更加容易。 在獨特的資料表示和有效的文件建立是非常重要的情況下,結合 HashSet 的效率和 IronPDF 的文件操作能力,可能會產生有創意的解決方案。

在 IronPDF 中使用 HashSet 的優點

  • 減少資料重複:透過確保只保留不同的元素,HashSets 有助於避免資料重複。 在處理龐大的資料集以移除重複資訊時,這是相當有幫助的。
  • Effective Lookup:使用 HashSet 可以以恆定時間平均複雜度執行插入、刪除和查詢等基本操作。 在處理不同大小的資料集時,這種效能非常重要。
  • 簡化文件製作: IronPDF 簡化了 C# PDF 文件的製作過程。 透過整合 HashSet 與 IronPDF,您可以建立快速有效的流程,為 PDF 製作原創且動態的內容。

現在,讓我們來看看在現實世界中使用 HashSet 與 IronPDF 可能會有用的情境。

以獨特的資料生成 PDF

using IronPdf;
using System;
using System.Collections.Generic;

class PdfGenerat或
{
    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>";
        f或each (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
using IronPdf;
using System;
using System.Collections.Generic;

class PdfGenerat或
{
    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>";
        f或each (var userName in uniqueUserNames)
        {
            htmlDocument += $"<li>{userName}</li>";
        }
        htmlDocument += "</ul></body></html>";
        return htmlDocument;
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在上述程式碼範例中,我們使用 HashSet uniqueUserNames儲存從陣列擷取的唯一使用者名稱。 HashSet 會自動排除重複的字詞。 接下來,我們使用 IronPDF 在 PDF 文件中建立這些不同使用者名稱的無序清單。 若要瞭解更多有關代碼的資訊,請參閱 使用 HTML 來建立 PDF

輸出

HashSet C# (How It W或ks F或 Developers):圖 3 - 輸出:UniqueUserNames.pdf

結論

總而言之,C# HashSet 資料結構是組織不同項目集合的有效工具。 與 IronPDF 搭配使用時,可為動態、獨一無二且效能最佳化的 PDF 文件製作創造新機會。

我們在所給的範例中說明了如何使用 HashSet 來保證資料的唯一性,同時使用 IronPDF 來建立 PDF 文件。 無論您是從事重複資料刪除、報表或動態內容管理,建立強大且有效的 C# 應用程式可能會從 HashSet 與 IronPDF 的結合中獲益。 當您進行更多調查時,請考慮到您可能利用此組合來改善應用程式可用性與功能的許多情境。

$799 Lite 版本的 IronPDF 具有永久授權、升級選項以及一年的軟體支援。 通過水印的 許可證上的試用期,瞭解 IronPDF 的價格、許可證和免費試用的詳細資訊。 請造訪Iron Software 網站,以取得更多關於 Iron Software 的資訊。

常見問題解答

在 C# 中生成 PDF 文件時,如何確保資料的唯一性?

在生成 PDF 文件之前,您可以使用 HashSet 來儲存獨特的資料元素,例如使用者名稱。這可確保重複的項目被移除,提供更乾淨、更精確的 PDF 內容。

在 IronPDF 中使用 HashSet 有什麼好處?

在 IronPDF 中使用 HashSet 可在創建 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 文件的建立,請使用 HashSet 來管理並篩選您的資料,以確保其唯一性,然後再傳送給 IronPDF 以產生最終的 PDF 文件。

HashSet 在動態內容管理中扮演什麼角色?

在動態內容管理中,HashSet 擔當著重要的角色,它可以確保資料保持唯一性,這對於文件生成、報告和維護資料完整性等任務而言至關重要。

如何在 C# 專案中安裝 IronPDF?

您可以使用 NuGet Package Manager 在 C# 專案中安裝 IronPDF,指令如下:Install-Package IronPdf,或使用 .NET CLI:dotnet add package IronPdf

HashSet 可以提高 C# 應用程式的效能嗎?

是的,HashSet 透過提供插入、刪除和查詢等基本操作的常時複雜性,可大幅改善 C# 應用程式的效能,使其能有效管理大型資料集。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。