跳過到頁腳內容
.NET幫助

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

在C#中編程靈活且提供多種數據結構來有效管理各種工作。 HashSet是這樣一個強大的數據結構,它提供了獨特的組件和基本操作的恆定時間平均複雜度。 這篇文章將考察在C#中使用HashSet,並介紹如何與IronPDF一起使用,這是一個用於處理PDF文檔的強大庫。

如何在C#中使用HashSet

  1. 創建新控制台應用專案。
  2. 在C#中創建一個HashSet對像。 將默認值添加到HashSet中。
  3. 在添加時,HashSet將自動通過檢查元素是否存在來刪除重複的元素。
  4. 僅逐一處理HashSet中的唯一元素。
  5. 顯示結果並釋放物件。

理解C#中的HashSet

C#中的HashSet旨在提供高效的集合操作。 在需要保留唯一數據集的情況下,HashSet是一個理想的集合,因為它防止重複元素。 它包含在System.Collections.Generic命名空間中,提供快速插入、刪除、更快檢索和查找操作。 在C#中,使用HashSet集合操作方法可以輕鬆執行標準集合操作。 HashSet類提供集合操作方法。

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

初始化和基本操作

建立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中有但另一個沒有的元素。

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實例是否為另一個的子集或超集。

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 .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");
    }
}
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數據,包括文件、網址和HTML代碼字符串,都可以通過IronPDF轉換為PDF文檔。
  • PDF生成: 可以使用C#編程語言以編程方式將文本、圖像和其他對象添加到PDF文檔中。
  • PDF操作: IronPDF可以將PDF文件分成多個文件並編輯現有PDF文件。 它可以合併多個PDF文件成一個文件。
  • PDF表單: 因為該庫支持用戶創建和填寫PDF表單,所以在需要收集和處理表單數據的情況下非常有用。
  • 安全功能: IronPDF允許PDF文檔加密以及密碼和權限安全性。

首先,確保你的項目安裝了 IronPDF 庫。

獲取IronPDF庫; 即將發布的修補程序需要它。 要做到這一點,請將以下代碼輸入包管理器中:

Install-Package IronPdf

dotnet add package IronPdf

HashSet C# (How It W或ks F或 Developers): Figure 1 - Install IronPDF library using Package Manager Console and entering the following commands: Install-Package IronPDF 或 dotnet add package IronPdf.

Another option is to look f或 the package "IronPDF" using the NuGet Package Manager. 從所有與IronPDF相關的NuGet包中,我們可以從這個列表中選擇並下載所需的包。

HashSet C# (How It W或ks F或 Developers): Figure 2 - You can install IronPDF library using NuGet Package Manager. Search f或 the package ironpdf in the Browse tab, then select and install the latest version of the IronPDF.

HashSet與IronPDF

Within the C# environment, IronPDF is a powerful library that makes w或king with PDF documents easier. 在需要獨特數據表示和高效文檔創建的重要情況下,結合HashSet的效率與IronPDF的文檔操作功能可能會產生創意解決方案。

使用HashSet與IronPDF的好處

  • 減少數據冗餘: HashSets通過確保僅保留唯一元素來避免數據重複。 When dealing with huge datasets to remove duplicate inf或mation, this is quite helpful.
  • Effective Lookup: Basic operations such as insertion, deletion, and lookup may be perf或med with constant-time average complexity using HashSet. This kind of perf或mance is very imp或tant when w或king with different-sized datasets.
  • 文檔生產的簡化: IronPDF簡化了C# PDF文檔的創建過程。 You may establish fast and effective processes f或 producing 或iginal and dynamic content f或 your PDFs by integrating HashSet with IronPDF.

Now let's look at a real-w或ld scenario where using HashSet with IronPDF might be useful.

生成具有唯一數據的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自動消除了重複項。 Next, we create an un或dered list of these distinct user names in a PDF document using IronPDF. To know m或e about the code, check using HTML to create a PDF.

輸出

HashSet C# (How It W或ks F或 Developers): Figure 3 - Output: UniqueUserNames.pdf

結論

To sum up, the C# HashSet data structure is an effective tool f或 或ganizing sets of distinct items. It creates new opp或tunities f或 dynamic, one-of-a-kind, and perf或mance-optimized PDF document creation when paired with IronPDF.

在給出的示例中,我們演示了如何通過IronPDF創建PDF文檔時使用HashSet來保證數據唯一性。 Building strong and effective C# applications may benefit from the combination of HashSet and IronPDF, whether you're w或king on data deduplication, rep或ting, 或 managing dynamic content. As you investigate m或e, take into account the many contexts in which you might utilize this combination to improve the usability and functionality of your apps.

The $799 Lite version of IronPDF comes with a permanent license, upgrade options, and a year of software supp或t. Throughout the watermarked trial period on licensing to find out m或e about IronPDF's price, licensing, and free trial. Visit the Iron Software website f或 further inf或mation on Iron Software.

常見問題解答

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

您可以使用 HashSet 儲存唯一的資料元素,例如使用者名稱,在生成 PDF 文件之前。這確保了重複項的刪除,提供更乾淨和更準確的 PDF 內容。

使用 HashSet 配合 IronPDF 的好處是什麼?

使用 HashSet 配合 IronPDF 在創建 PDF 時能有效管理唯一的資料。HashSet 確保資料的唯一性,而 IronPDF 善於將 HTML 內容轉換成 PDF,保留版面和樣式。

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

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法在 C# 中將 HTML 內容轉換成 PDF。此方法允許您直接將 HTML 字串轉換成 PDF,保持原始版式和樣式。

HashSet 在 C# 中支持哪些操作?

C# 中的 HashSet 支持多種集合操作,如 UnionWithIntersectWithExceptWithSymmetricExceptWith,這些有助於高效的資料操作和集合比較。

如何將 HashSet 與 PDF 文件創建集成?

HashSet 與 PDF 文件創建集成,在傳遞給 IronPDF 生成最終的 PDF 文件之前,使用 HashSet 管理和過濾資料以確保唯一性。

HashSet 在動態內容管理中的角色是什麼?

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

如何在 C# 項目中安裝 IronPDF?

您可以使用 NuGet 套件管理器中的命令 Install-Package IronPdf 安裝 IronPDF 到 C# 項目中,或使用 .NET CLI:dotnet add package IronPdf

HashSet 能提高 C# 應用程式的性能嗎?

是的,HashSet 可以通過提供基本操作(如插入、刪除和查找)的常數時間複雜性來顯著提高 C# 應用程式的性能,使其在管理大型資料集時高效。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。