跳至页脚内容
.NET 帮助

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

在 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 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 f或 .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");
    }
}
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 库; 即将修补的版本需要它。 为此,在包管理器中输入以下代码:

Install-Package IronPdf

dotnet add package IronPdf

HashSet C#(如何为开发人员工作):图 1 - 使用包管理器控制台安装 IronPDF 库并输入以下命令:Install-Package IronPDF或dotnet 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 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#(如何为开发人员工作):图 3 - 输出:UniqueUserNames.pdf

结论

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

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

$799 版本的 IronPDF 附带永久许可证、升级选项和一年的软件支持。 在许可的试用期期间可以访问更多有关 IronPDF 的价格、许可和免费试用的信息。 访问 Iron Software 网站获取有关 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 文档创建相结合,使用 HashSet 管理和过滤您的数据以确保唯一性,然后再传递给 IronPDF 生成最终的 PDF 文档。

HashSet 在动态内容管理中的作用是什么?

在动态内容管理中,HashSet 扮演着保证数据唯一性的关键角色,这对于文档生成、报告和保持数据完整性等任务来说至关重要。

如何在 C# 项目中安装 IronPDF?

您可以通过 NuGet 包管理器使用命令 Install-Package IronPdf,或通过 .NET CLI 使用命令 dotnet add package IronPdf 在 C# 项目中安装 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 和 Iron Suite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。