跳至頁尾內容
.NET 幫助

C# HashSet(開發者使用方法)

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}");
    }
}
$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);
        }
    }
}
$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);
        }
    }
}
$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);
        }
    }
}
$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);
        }
    }
}
$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}");
    }
}
$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);
        }
    }
}
$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");
    }
}
$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;
    }
}
$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文件時確保資料的唯一性?

您可以使用HashSet來儲存唯一資料元素,例如使用者名,然後再產生 PDF 文件。這樣可以確保刪除重複條目,從而提供更簡潔、更準確的 PDF 內容。

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

在 IronPDF 中使用HashSet可以有效率地管理建立 PDF 時的唯一資料。 HashSet 確保資料的唯一性,而 IronPDF 則擅長將 HTML 內容轉換為 PDF, HashSet保留佈局和樣式。

如何在 C# 中將 HTML 內容轉換為 PDF?

您可以使用 IronPDF 的RenderHtmlAsPdf方法在 C# 中將 HTML 內容轉換為 PDF。此方法可讓您直接將 HTML 字串轉換為 PDF,並保持原始佈局和樣式。

C# 中的 HashSet 支援哪些操作?

C# 中的HashSet支援各種集合操作,例如UnionWithIntersectWithExceptWithSymmetricExceptWith ,這些操作有助於有效地進行資料操作和集合比較。

如何將 HashSet 與 PDF 文件建立功能整合?

若要將HashSet與 PDF 文件建立集成,請使用HashSet管理和篩選資料的唯一性,然後再傳遞給 IronPDF 以產生最終的 PDF 文件。

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

在動態內容管理中, HashSet透過確保資料的唯一性發揮至關重要的作用,這對於文件產生、報告和維護資料完整性等任務至關重要。

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

您可以使用 NuGet 套件管理器在 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 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。