C# 集合(對於開發者的運行原理)
C# 已成為眾多可用的程式語言中,開發人員常用且靈活的選擇。 集合的概念是 C# 廣泛程式庫和框架的核心,這是該語言的主要優勢之一。 在 C# 中,集合對於有效儲存和組織資料至關重要。 它們為開發人員提供了一系列有效的工具,以解決複雜的程式設計問題。 我們將在本文中深入探討集合,涵蓋其功能、型別和最佳使用策略。
如何使用 C# 集合
- 建立一個新的控制台應用專案。
- 在 C# 中為集合建立一個物件。
- 將值新增到集合類中,該類可以儲存多組物件。
- 處理如新增、移除、排序等的值操作。
- 顯示結果並釋放物件。
C#: 理解集合
C# 中的集合是容器,讓程式員可以操作和儲存一組物件類別。 這些物件在許多程式環境中具有靈活性和適應性,並且可能是相同或不同型別的。 大多數集合類別實現了 C# 中的 System 命名空間的元件,這意味著導入像是 System.Collections 和 System.Collections.Generic 等命名空間,提供了各種集合類別,既有泛型也有非泛型的。 集合還允許動態記憶體分配、增加、搜尋和排序集合類中的項目。
非泛型集合型別
ArrayList、Hashtable 和 Queue 是一些在 C# 中的非泛型集合類別,它們在語言的最初版本中被包含進來。 這些集合提供了一種替代方案,可以明確地定義您希望保留和處理的項目型別。 然而,開發人員經常選擇泛型集合,因為它們的性能優越且型別安全。
泛型集合
C# 的後續版本包含泛型集合,以克服非泛型集合的缺點。 它們在編譯期間提供型別安全,並讓開發人員可以處理具有緊密型別的資料。 泛型集合類如 List, Dictionary<TKey, TValue>, Queue, 和 Stack 等是常用的。 這些集合是現代 C# 開發中的常用選擇,因為它們提供了更好的性能和編譯時型別驗證。
關鍵的 C# 集合型別
1. List
List 類是一個動態陣列,旨在實現快速且簡單的元素插入和刪除。 由於其提供了過濾、搜尋和操作元件的方法,是需要可調整大小集合的情況下的靈活選擇。
// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
// Creating a list with integers and adding/removing elements
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6); // Adds element '6' to the end
numbers.Remove(3); // Removes the first occurrence of the element '3'
' Creating a list with integers and adding/removing elements
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 the first occurrence of the element '3'
2. Dictionary<TKey, TValue>
Dictionary<TKey, TValue> 類表示具有快速查找速度的鍵值對集合。 其常用於需要通過唯一鍵值快速存取資料的情況。 此鍵用於存取字典中的元素。
// Creating a dictionary mapping names to ages
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
// Creating a dictionary mapping names to ages
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
' Creating a dictionary mapping names to ages
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
3. Queue 和 Stack
泛型 Queue 和泛型 Stack 類分別實現了先進先出集合(FIFO)和後進先出(LIFO)模式。 它們可以根據應用的需求以某種順序管理項目。
// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");
// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
// Creating and manipulating a queue
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task 1"); // Adding to the queue
tasks.Enqueue("Task 2");
// Creating and manipulating a stack
Stack<double> numbers = new Stack<double>();
numbers.Push(3.14); // Adding to the stack
numbers.Push(2.71);
' Creating and manipulating a queue
Dim tasks As New Queue(Of String)()
tasks.Enqueue("Task 1") ' Adding to the queue
tasks.Enqueue("Task 2")
' Creating and manipulating a stack
Dim numbers As New Stack(Of Double)()
numbers.Push(3.14) ' Adding to the stack
numbers.Push(2.71)
4. HashSet
HashSet 類表示在無序集合中排列的唯一項目。 它提供了有效的方法來執行集合運算,如差集、聯集和交集。
// Creating hashsets and performing a union operation
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
// Creating hashsets and performing a union operation
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
' Creating hashsets and performing a union operation
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
IronPDF

一個名為 IronPDF 的 C# 程式庫,使在 .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
IronPDF 的主要功能包括:
- 將 HTML 轉換為 PDF:借助 IronPDF,程式員可以用 HTML 文字建立 PDF 文件,包括 CSS 和 JavaScript。 這對於那些已經熟悉網站開發工具並希望使用 HTML 和 CSS 建立 PDF 的人特別有用。
- PDF 資料生成與操作:該程式庫提供了從頭開始程式化建立 PDF 文件的能力。 此外,它也有助於編輯現有的 PDF,允許進行如文字提取、水印新增、拆分 PDF 等操作。
- 優異的渲染:IronPDF 使用渲染引擎來生成高品質的 PDF 輸出,確保最終文件保留清晰度和視覺完整性。
- 跨平台相容性:IronPDF 被設計為能與 .NET Core 和 .NET Framework 都能運作,使其可以用於各種應用及多種平台上。
- 性能優化:即使處理大型或複雜的 PDF 文件,該程式庫也被設計為能提供高效的 PDF 生成與渲染。
要獲知更多有關 IronPDF 資料,可參考 IronPDF Documentation。
IronPDF 的安裝
using Package Manager Console 或 NuGet Package Manager 先安裝 IronPDF 程式庫:
Install-Package IronPdf
using NuGet Package Manager 搜尋套件 "IronPDF" 是另一個選擇。 我們可以從中選擇並下載所需的套件,從所有與 IronPDF 相關的 NuGet 套件中挑選。

使用集合與 IronPDF 建立文件
在深入了解 IronPDF 的介面之前,理解集合在資料結構及組織中的作用至關重要。 開發人員可通過使用集合以組織良好的方式儲存、檢索和修改項目群組。 由於有多種型別可用,如 List、Dictionary<TKey, TValue> 和 HashSet,開發人員可選擇最符合其需求的集合。
想像一下,您必須建立一個包含銷售交易列表的報告。 資料可借助 List
// Define the Transaction class
public class Transaction
{
public string ProductName { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
// Create a list of transactions
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
};
// Define the Transaction class
public class Transaction
{
public string ProductName { get; set; }
public decimal Amount { get; set; }
public DateTime Date { get; set; }
}
// Create a list of transactions
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
};
' Define the Transaction class
Public Class Transaction
Public Property ProductName() As String
Public Property Amount() As Decimal
Public Property [Date]() As DateTime
End Class
' Create a list of transactions
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)
}
}
在 PDF 中,我們將建立一個簡單的表格,列出每一筆交易的商品名稱、交易金額和日期。
using IronPdf;
// Create a PDF document renderer
var pdfDocument = new 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);
// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
using IronPdf;
// Create a PDF document renderer
var pdfDocument = new 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);
// Specify the file path to save the PDF
string pdfFilePath = "transactions_report.pdf";
pdf.SaveAs(pdfFilePath);
Imports IronPdf
' Create a PDF document renderer
Private pdfDocument = New HtmlToPdf()
' HTML content with a table populated by data from the 'transactions' list
Private 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)
' Specify the file path to save the PDF
Dim pdfFilePath As String = "transactions_report.pdf"
pdf.SaveAs(pdfFilePath)
開發人員可以選擇將建立的 PDF 文件儲存到磁碟或向使用者顯示。 IronPDF 提供了多種輸出選項,包括瀏覽器串流、文件儲存和雲儲存整合。

上述畫面顯示了上述程式碼生成的輸出。 要了解更多有關程式碼的資訊,請參考 Using HTML to Create a PDF Example。
結論
通過將集合與 IronPDF 結合,提供了眾多動態文件生成的機會。 開發人員可通過利用集合有效組織和管理資料,而 IronPDF 可以輕鬆建立視覺上美觀的 PDF 文件。 IronPDF 和集合的綜合能力為 C# 應用中的動態內容生成提供了可靠且靈活的解決方案,無論您是生產發票、報告或其他文件。
IronPDF 的 $999 Lite 版包括一年軟體支援,升級選擇和永久授權。 使用者還有機會在加水印的試用期間中,在現實情況下評估產品。 要了解更多有關 IronPDF 的費用、授權和免費試用,請造訪 IronPDF Licensing Information。 欲了解更多關於 Iron Software 的資訊,請前往 Iron Software Website。
常見問題
什麼是 C# 中的集合?為什麼它們很重要?
C# 中的集合對於資料儲存和組織至關重要,為開發者提供了有效處理複雜程式設計挑戰的工具。它們允許動態記憶體分配並輕鬆操作資料集。
C# 中非泛型集合與泛型集合之間有何不同?
非泛型集合,如 ArrayList 和 Hashtable,型別安全性較低,可以儲存任何物件型別。泛型集合,如 List 和 Dictionary,透過強制資料型別一致性提供型別安全性和增強效能。
如何在 C# 中建立泛型列表?
在 C# 中可以使用 List 類別建立泛型列表。例如,可以使用 List 建立一個整數列表。
如何在C#中將HTML轉換成PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。它還支援將 HTML 檔案和 URL 轉換為 PDF 文件,保持佈局和樣式的完整性。
在 C# 中使用集合的一些最佳實踐是什麼?
在 C# 中使用集合的最佳實踐包括針對您的需求選擇合適的集合型別,例如使用 Dictionary 來存取鍵值對和使用 List 來管理有序列表,確保通過適當的記憶體管理來釋放不再需要的集合。
集合可以如何增強 C# 應用程式中的 PDF 建立?
集合可以有效地組織資料來建立文件。例如,使用 List 統整銷售資料,可以借助 IronPDF 生成綜合的 PDF 報告,優化資料管理和展示。
IronPDF 有哪些授權選項?
IronPDF 提供了一年支援和升級的 Lite 授權,還有帶水印的試用版本供評估。這些選項讓開發者可以在專案中測試和實施 IronPDF 的功能。
如何在 .NET 專案中安裝 IronPDF?
您可以使用 NuGet 套件管理器在 .NET 專案中安裝 IronPDF,指令為 Install-Package IronPdf。或者,您可以在 NuGet 套件管理器中搜尋 'IronPDF' 以將其新增到您的專案中。




