IRONSOFTWAREHOME
開發者更新

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

在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 for membership of an element
        bool containsThree = numbers.Contains(3);

        Console.WriteLine($"Contains 3: {containsThree}");
    }
}

使用集合初始化

使用現有集合作為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);
        }
    }
}

與另一個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);
        }
    }
}

與另一個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);
        }
    }
}

與另一個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);
        }
    }
}

檢查子集或超集:

使用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}");
    }
}

對稱差集

使用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);
        }
    }
}

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");
    }
}

IronPDF的功能

  • **HTML轉PDF:**任何型別的HTML資料,包括檔案、網址和HTML程式碼字串,都可以使用IronPDF轉換為PDF檔案。
  • **PDF產生:**可以使用C#程式語言程式化地將文字、圖像和其他物件加入到PDF文件中。
  • **PDF操作:**IronPDF可以將一個PDF文件分割成多個檔案,並且可以編輯已存在的PDF文件。 它可以將多個PDF檔案合併成一個檔案。
  • **PDF表單:**因為該庫允許使用者建立和填寫PDF表單,在需要收集和處理表單資料的情況下非常有用。
  • **安全功能:**IronPDF允許對PDF文件進行加密以及密碼和權限的安全設置。

安裝IronPDF

獲取IronPDF程式庫; 即將發布的補丁需要它。 為此,請輸入以下程式碼到Package Manager中:

PM > Install-Package IronPdf

or

dotnet add package IronPdf

HashSet C# (How It Works For Developers): Figure 1 - Install IronPDF library using Package Manager Console and entering the following commands: "Install-Package IronPdf" or ".NET 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結合,您可以快速有效地建立過程以產生您的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;
    }
}

在上述程式碼範例中,我們使用HashSet uniqueUserNames保存從陣列中檢索的唯一使用者名。 HashSet自動消除重複項目。 接下來,我們在PDF文件中使用IronPDF建立這些獨特使用者名的無序列表。 要了解有關程式碼的更多資訊,請查看使用HTML建立PDF

輸出

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

結論

總結來說,C#中的HashSet資料結構是一種有效的工具,用於組織一組獨特的物件。 當與IronPDF結合使用時,它在動態、獨特和效能優化的PDF文件建立中創造了新的機會。

我們展示了如何使用HashSet來保證資料獨特性,並使用IronPDF來建立PDF文件。 無論您是執行資料去重、報告還是動態內容管理,HashSet和IronPDF的結合都可以為深入和強大的C#應用提供幫助。 當您進一步探索時,請考慮在各種上下文中如何利用這種結合來提高您的應用程式的可用性和功能。

$999 IronPDF的Lite版本附帶永久授權、升級選項和一年的軟體支援。 在帶水印的試用許可期間,有關IronPDF的價格、許可和免費試用的更多資訊。 存取Iron Software網站了解Iron Software的更多資訊。

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立