IRONSOFTWAREHOME
开发者更新

HashSet C#(开发人员如何使用)

Jacob Mellor,Team Iron 的首席技术官
Jacob Mellor
Updated: 2026年4月23日

在 C# 中编程是灵活的,提供了多种数据结构来有效管理各种任务。 HashSet 是一种强大的数据结构,提供了独特的组件和基本操作的常时间平均复杂度。 本文将探讨在 C# 中使用 HashSet 以及如何与处理 PDF 文档的强大库 IronPDF 结合使用。

如何在 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 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 的并集

using 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:");
        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 的差集

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

检查子集或超集: using 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 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转换方面表现出色,确保精确保留原始布局和样式。 它非常适合从基于Web的内容中创建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 数据,包括文件、URL 和 HTML 代码字符串,都可以用 IronPDF 转换为 PDF 文档。
  • **PDF 生成:**可以程序化地使用 C# 编程语言将文本、图像和其他对象加入 PDF 文档。
  • **PDF 操作:**IronPDF 可以将 PDF 文件分割为多个文件并编辑现有的 PDF 文件。 它可以将多个 PDF 文件合并为一个文件。
  • **PDF 表单:**由于该库支持构建和填写 PDF 表单,因此在需要收集和处理表单数据的场景中很有用。
  • **安全功能:**IronPDF 允许对 PDF 文档进行加密,以及密码和权限安全。

安装IronPDF

获取 IronPDF 库; 即将修补的版本需要它。 为此,在包管理器中输入以下代码:

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 会自动消除重复项。 接下来,我们使用 IronPDF 在 PDF 文档中创建这些独特用户名的无序列表。 要了解有关代码的更多信息,请查看使用 HTML 创建 PDF。

输出

HashSet C# (开发人员如何使用): 图3 - 输出: UniqueUserNames.pdf

结论

总结来说,C# 的 HashSet 数据结构是组织独特项目集的有效工具。 当与 IronPDF 配对时,为动态、独特和性能优化的 PDF 文档创建带来了新机会。

我们展示了如何使用 HashSet 来保证数据的唯一性,同时使用IronPDF 来创建 PDF 文档,在前面给出的例子中。 无论您是在进行数据去重、报告还是管理动态内容,HashSet 和 IronPDF 的结合都可能为构建强大和高效的 C# 应用程序带来好处。 当您进一步探索时,请考虑您可能利用这种组合来改善应用程序可用性和功能的多个上下文。

IronPDF的$999 Lite版本附带永久许可证、升级选项和一年的软件支持。 在许可的试用期期间可以访问更多有关 IronPDF 的价格、许可和免费试用的信息。 访问 Iron Software 网站获取有关 Iron Software 的更多信息。

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

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥。

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

OR
bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥。
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索 “IronPDF”
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

或在此处下载 Windows 安装程序。

  1. 下载并解压 IronPDF 到您的解决方案目录中的 ~/Libs 之类的位置
  2. 在 Visual Studio 解决方案资源管理器中,右键点击引用。选择浏览,“IronPDF.dll”

$999 起