.NET 帮助

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

发布 2024年三月6日
分享:

简介

在众多可用的编程语言中,C# 已成为开发人员最常用、适应性最强的语言。集合的概念是 C# 广泛的库和框架的核心,也是该语言的主要优势之一。在 C# 中,集合对于有效存储和组织数据至关重要。它们为开发人员解决具有挑战性的编程问题提供了多种有效工具。在本篇文章中,我们将进一步深入研究集合,包括集合的功能、类型和最佳使用策略。

如何使用 C#集合

1.创建一个新的控制台应用程序项目。

2.用 C# 为集合创建一个对象。

3.将值添加到集合类,它可以存储多组对象

4.处理值操作,如添加、删除、排序等

5.显示结果并处理对象。

C#:了解收藏

在 C# 中,集合是让程序员处理和存储对象类集的容器。这些对象非常灵活,可适应多种编程设置,它们可能是相同的,也可能是不同种类的。在 C# 中,大多数集合类都实现了 System 的组件,这意味着要导入命名空间,如 System.Collections 和 System.Collections.Generic,后者提供了各种通用和非通用的集合类。集合还允许动态内存分配、添加、搜索和排序集合类中的项目。

非通用采集类型

数组列表(ArrayList)、哈希表(Hashtable)和队列(Queue)是 C# 中的一些非通用集合类,它们包含在 C# 语言的最初迭代中。除了明确定义要保存和处理的内容外,这些集合提供了另一种选择。不过,开发人员经常选择泛型集合,因为它们具有卓越的性能和类型安全性。

通用集合

C# 的后期迭代包含了泛型集合,以克服非泛型集合的缺点。它们在编译过程中提供了类型安全,让开发人员可以处理严格类型的数据。泛型集合类 List词典<TKey, TValue>, 队列和栈堆是经常使用的几个集合。这些集合是当代 C# 开发中的首选,因为它们提供了更好的性能和编译时类型验证。

键 C&num;集合类型

1.清单

List 是一个动态数组,能方便快捷地插入和移除元素。类。对于需要可调整大小的集合的情况,它是一个灵活的选择,因为它提供了过滤、搜索和操作组件的方法。

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // adds element '6' to the end
numbers.Remove(3); // removes all the items that are '3'
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
numbers.Add(6) ' adds element '6' to the end
numbers.Remove(3) ' removes all the items that are '3'
VB   C#

2.dictionary<TKey, TValue> 字典

Dictionary<TKey, TValue> 类可快速查找键值对集合。在通过特殊键值快速访问数据至关重要的情况下,经常使用该类。该键值用于访问字典中的元素。

Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // the string "John" is the key, that can access the value 25
ageMap ["Jane"] = 30; // setting the key "Jane" to hold the value 30
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap.Add("John", 25); // the string "John" is the key, that can access the value 25
ageMap ["Jane"] = 30; // setting the key "Jane" to hold the value 30
Dim ageMap As New Dictionary(Of String, Integer)()
ageMap.Add("John", 25) ' the string "John" is the key, that can access the value 25
ageMap ("Jane") = 30 ' setting the key "Jane" to hold the value 30
VB   C#

3.队列和栈堆

先进先出收集 (先进先出)和后进先出 (后进先出) 分别通过通用队列和队列范例来实现。和通用堆栈类。它们可用于根据应用程序的需要按一定顺序管理项目。

Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Queue<string> tasks = new Queue<string>(); // creating a queue class
tasks.Enqueue("Task 1"); // adding to the queue
tasks.Enqueue("Task 2");
Stack<double> numbers = new Stack<double>(); // creating a stack class
numbers.Push(3.14); // adding to the stack
numbers.Push(2.71);
Dim tasks As New Queue(Of String)() ' creating a queue class
tasks.Enqueue("Task 1") ' adding to the queue
tasks.Enqueue("Task 2")
Dim numbers As New Stack(Of Double)() ' creating a stack class
numbers.Push(3.14) ' adding to the stack
numbers.Push(2.71)
VB   C#

4. HashSet

在无序集合中排列的唯一项由 HashSet 表示类。它提供了执行集合运算(如差分、联合和相交)的有效方法。

HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // combining setA and setB
HashSet<int> setA = new HashSet<int> { 1, 2, 3, 4 };
HashSet<int> setB = new HashSet<int> { 3, 4, 5, 6 };
HashSet<int> unionSet = new HashSet<int>(setA);
unionSet.UnionWith(setB); // combining setA and setB
Dim setA As New HashSet(Of Integer) From {1, 2, 3, 4}
Dim setB As New HashSet(Of Integer) From {3, 4, 5, 6}
Dim unionSet As New HashSet(Of Integer)(setA)
unionSet.UnionWith(setB) ' combining setA and setB
VB   C#

IronPDF

C# Collection(如何为开发人员工作):图 1 - IronPDF 网站页面

一个名为 IronPDF 它能在 .NET 应用程序中轻松创建、编辑和显示 PDF 文档。它提供多种许可选择、跨平台兼容性、高质量渲染以及 HTML 到 PDF 的转换。IronPDF 的用户友好 API 使处理 PDF 文件变得更容易,这使它成为 C# 开发人员的有用工具。

IronPDF 的突出特点是它的 HTML 转 PDF 功能,维护所有布局和样式。它能从网页内容生成 PDF,是报告、发票和文档的理想选择。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");
    }
}
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
VB   C#

IronPDF 的主要功能包括

  • 将 HTML 转换为 PDF:使用 IronPDF,程序员可以从 HTML 文本(包括 CSS 和 JavaScript)创建 PDF 文档。那些已经熟悉网络开发工具并希望使用 HTML 和 CSS 创建 PDF 文件的人会发现这非常有用。
  • PDF 生成和操作:该库能够以编程方式从头开始创建 PDF 文档。此外,它还便于编辑已存在的 PDF,可进行文本提取、添加水印、分割 PDF 等操作。
  • 卓越的渲染功能:IronPDF 使用渲染引擎生成最高质量的 PDF 输出,确保最终文档保持清晰度和视觉完整性。
  • 跨平台兼容性:IronPDF 可在各种应用程序和平台上使用,因为它可以在.NET Core 和.NET Framework 上运行。

  • 性能优化:即使在处理大型或复杂的 PDF 文档时,该库也能提供高效的 PDF 制作和渲染。

要了解有关 IronPDF 文档的更多信息,请参阅 *这里***.

IronPDF 的安装

首先使用软件包管理器控制台或 NuGet 软件包管理器安装 IronPDF 库:

Install-Package IronPdf

C# Collection(如何为开发人员工作):图 2 - 使用软件包管理器控制台安装 IronPDF

使用 NuGet 软件包管理器搜索软件包 "IronPDF "也是一种选择。我们可以从与 IronPDF 相关的所有 NuGet 软件包列表中选择并下载所需的软件包。

C# Collection(如何为开发人员工作):图 3 - 使用 NuGet 软件包管理器安装 IronPDF

使用 IronPDF 利用集合创建文档

在了解 IronPDF 界面之前,了解集合在数据结构和组织中的作用至关重要。通过使用集合,开发人员可以有组织地存储、检索和修改分组。有这么多不同的类型可供选择,如 List词典<TKey, TValue>和 HashSet因此,开发人员可以选择最符合其要求的集合。

试想一下,你必须创建一个包含销售交易列表的报告。可以使用列表作为进一步处理和显示的基础。

public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
public class Transaction
{
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
List<Transaction> transactions = new List<Transaction>
{
    new Transaction { ProductName = "Product A", Amount = 100.50m, Date = DateTime.Now.AddDays(-2) },
    new Transaction { ProductName = "Product B", Amount = 75.20m, Date = DateTime.Now.AddDays(-1) },
    // Add more transactions as needed
};
Public Class Transaction
	Public Property ProductName() As String
	Public Property Amount() As Decimal
	Public Property [Date]() As DateTime
End Class
Private transactions As New List(Of Transaction) From {
	New Transaction With {
		.ProductName = "Product A",
		.Amount = 100.50D,
		.Date = DateTime.Now.AddDays(-2)
	},
	New Transaction With {
		.ProductName = "Product B",
		.Amount = 75.20D,
		.Date = DateTime.Now.AddDays(-1)
	}
}
VB   C#

在 PDF 文件中,我们将制作一个简单的表格,列出每种产品的名称、交易金额和日期。

var pdfDocument = new IronPdf.HtmlToPdf();
// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";
// Convert HTML to PDF
PdfDocument pdf =  pdfDocument.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs(pdfFilePath);
var pdfDocument = new IronPdf.HtmlToPdf();
// HTML content with a table populated by data from the 'transactions' list
string htmlContent = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>";
foreach (var transaction in transactions)
{
    htmlContent += $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>";
}
htmlContent += "</table>";
// Convert HTML to PDF
PdfDocument pdf =  pdfDocument.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs(pdfFilePath);
Dim pdfDocument = New IronPdf.HtmlToPdf()
' HTML content with a table populated by data from the 'transactions' list
Dim htmlContent As String = "<table><tr><th>Product Name</th><th>Amount</th><th>Date</th></tr>"
For Each transaction In transactions
	htmlContent &= $"<tr><td>{transaction.ProductName}</td><td>{transaction.Amount}</td><td>{transaction.Date.ToShortDateString()}</td></tr>"
Next transaction
htmlContent &= "</table>"
' Convert HTML to PDF
Dim pdf As PdfDocument = pdfDocument.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs(pdfFilePath)
VB   C#

开发人员可以选择将 PDF 文档保存到磁盘,或在制作完成后向用户显示。IronPDF 提供多种输出选择,包括浏览器流、文件保存和云存储集成。

C# Collection(如何为开发人员工作):图 4 - 上一段代码输出的 PDF

上图显示了上述代码生成的输出结果。要了解代码的更多信息,请参阅 *这里***.

结论

集合与 IronPDF 的结合为动态文档制作提供了大量机会。开发人员可以利用集合有效地管理和组织数据,而 IronPDF 则可以轻松地创建视觉美观的 PDF 文档。IronPDF 和集合的组合功能为 C# 应用程序中的动态内容制作提供了可靠且适应性强的解决方案,无论您制作的文档类型是发票、报告还是其他。

IronPDF 的"$liteLicense "精简版包括一年的软件支持、升级选项和永久许可证。在带水印的试用期内,用户还有机会在实际环境中对产品进行评估。要了解有关 IronPDF 成本、许可和免费试用的更多信息,请访问许可 .有关 Iron 软件的更多信息,请访问以下网站 网站.

< 前一页
MSTest C#(它对开发人员的工作原理)
下一步 >
C#空条件运算符(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >