跳過到頁腳內容
.NET幫助

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

C# 已成為眾多可用程式語言中,開發人員流行且靈活的選擇。 集合的概念是 C# 廣泛程式庫及框架的核心,這是該語言主要的優勢之一。 在 C# 中,集合對於有效地儲存和組織數據至關重要。 它們為開發人員提供多種有效工具來解決挑戰性的程式設計問題。 在這篇文章中,我們將更深入地探討集合,介紹它們的特徵、類型及最佳使用策略。

如何使用 C# 集合

  1. 創建新控制台應用專案。
  2. 在 C# 中為集合創建一個物件。
  3. 將值添加到集合類中,可以儲存多組物件。
  4. 處理添加、移除、排序等值操作。
  5. 顯示結果並釋放物件。

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'
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

IronPDF

C# Collection (開發人員運作方式):圖 1 - 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
$vbLabelText   $csharpLabel

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 文檔

IronPDF 的安裝

首先使用軟件包管理器控制台或 NuGet 軟件包管理器安裝 IronPDF 資料庫:

Install-Package IronPdf

C# Collection (開發人員運作方式):圖 2 - 使用軟件包管理器控制台安裝 IronPDF

使用 NuGet 軟件包管理器搜尋 "IronPDF" 軟件包是另一種選擇。 於此列表中,我們可從所有與 IronPDF 相關的 NuGet 軟件包中選擇並下載必要的軟件包。

C# Collection (開發人員運作方式):圖 3 - 使用 NuGet 軟件包管理器安裝 IronPDF

使用 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)
	}
}
$vbLabelText   $csharpLabel

在 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)
$vbLabelText   $csharpLabel

開發人員在生成 PDF 後可以選擇將其保存到磁碟或向用戶顯示。 IronPDF 提供幾種輸出選項,包括瀏覽器流媒體、文件保存和雲端存儲整合。

C# Collection (開發人員運作方式):圖 4 - 上述代碼生成的輸出 PDF

上面的螢幕顯示了該代碼生成的輸出。 如需了解更多代碼,請參考 使用 HTML 創建 PDF 示例

結論

結合 IronPDF 使用集合創建動態文件的眾多可能性。 開發人員可以有效地管理和組織數據,IronPDF 使創建視覺美觀的 PDF 文件變得容易。 IronPDF 和集合的組合實力提供了一個可靠和靈活的解決方案,用於 C# 應用中動態內容的生成,無論您生成的是什麼樣的文件——發票、報告或其他內容。

IronPDF 的 $799 輕量版本包含一年軟件支持、升級選項並擁有永久許可。 用戶還有機會在附有水印的試用期內在實際環境中評估產品的真實效力。 有關 IronPDF 的成本、授權和免費試用的更多信息,請訪問 IronPDF 授權信息。 如需更多有關 Iron Software 的信息,請前往 Iron Software 網站

常見問題解答

什麼是 C# 中的集合,為什麼它們很重要?

C# 中的集合對於數據儲存和組織至關重要,為開發人員提供工具,以高效應對複雜的編程挑戰。它們允許動態內存分配和數據集的輕鬆操作。

C# 中非泛型集合和泛型集合之間有何不同?

非泛型集合如ArrayListHashtable類型安全性較差,可以存儲任何對象類型。泛型集合如ListDictionary通過強制數據類型一致性來提供類型安全性和提升性能。

如何在 C# 中創建泛型列表?

可以使用List類創建 C# 中的泛型列表。例如,可以使用List numbers = new List { 1, 2, 3 };創建一個整數列表。

怎樣在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的RenderHtmlAsPdf方法將 HTML 字符串轉換為 PDF。它還支持將 HTML 文件和 URL 轉換為 PDF 文檔,保持佈局和樣式的完整性。

使用 C# 集合的一些最佳實踐是什麼?

使用 C# 集合的最佳實踐包括選擇適合您需求的集合類型,例如使用Dictionary來處理鍵值對,以及使用List來處理有序列表,並通過在不再需要時釋放集合來確保適當的內存管理。

集合如何在 C# 應用程序中增強 PDF 創建?

集合可以高效組織數據以創建文檔。例如,使用List來彙編銷售數據可以促進生成全面的 PDF 報告,通過 IronPDF 簡化數據管理和呈現。

IronPDF 的許可選擇有哪些?

IronPDF 提供帶有一年支持和升級的 Lite 許可證,以及用於評估的帶水印試用版。這些選項使開發人員能夠在他們的項目中測試和實現 IronPDF 的功能。

如何在 .NET 專案中安裝 IronPDF?

您可以使用命令Install-Package IronPdf通過 NuGet 包管理器在 .NET 項目中安裝 IronPDF。或者,您可以在 NuGet 包管理器中搜索 'IronPDF' 來將其添加到您的項目中。

Curtis Chau
技術作家

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

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