跳過到頁腳內容
.NET幫助

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

在眾多可用的程式語言中,C# 已經成為受開發人員歡迎、適應性強的選擇。 集合的概念是 C# 廣泛的函式庫和框架的核心,也是該語言的主要優勢之一。 在 C# 中,集合是有效儲存和組織資料的必要條件。 這些工具為開發人員提供各種有效的工具,以解決具有挑戰性的程式設計問題。 我們將在本篇文章中進一步深入探討集合,涵蓋其功能、類型和最佳使用策略。

如何使用 C# 集合

1.建立新的 Console App 專案。 2.在 C# 中為集合建立一個物件。 3.將值加入集合類,集合類可儲存多組物件。 4.處理數值操作,如新增、移除、排序等。 5.顯示結果並處理物件。

C#:瞭解集合

C# 中的集合是讓程式設計師處理和儲存物件類別集的容器。 這些物件具有彈性,可適用於許多程式設計環境,而且可能是相同或不同的種類。 大多數的集合類別都在 C# 中實作 System 命名空間的元件,也就是導入命名空間,例如 System.Collections 和 System.Collections.Generic,其中提供了各種泛型和非泛型的集合類別。 集合也允許動態記憶體分配、在集合類別中新增、搜尋和排序項目。

非通用集合類型

ArrayList、Hashtable 和 Queue 是 C# 中可用的幾個非一般集合類別,這些類別包含在 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.字典<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.佇列和堆疊

先入先出集合 (FIFO) 和後入先出 (LIFO) 模式分別由泛型 Queue和泛型 Stack類別實作。 這些工具可用於根據應用程式的需求,以特定順序管理項目。

// 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。

!a href="/static-assets/pdf/blog/csharp-collection/csharp-collection-1.webp">C# Collection (How It Works For Developers):圖 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 文字(包括 CSS 和 JavaScript)建立 PDF 文件。 這對於那些已經熟悉網頁開發工具並希望使用 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 (How It Works For Developers):圖 2 - 使用套件管理員控制台安裝 IronPdf

使用 NuGet Package Manager 搜尋套件"IronPDF"是另一個選擇。 我們可以從與 IronPDF 相關的所有 NuGet 套件中,選擇並下載此清單中所需的套件。

C# Collection (How It Works For Developers):圖 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 (How It Works For Developers):圖 4 - 從之前的程式碼輸出 PDF

上面的畫面顯示了由上述程式碼產生的輸出。 若要瞭解程式碼的更多資訊,請參閱 使用 HTML 建立 PDF 的範例

結論

將集合與 IronPDF 相結合,可實現大量的動態文件製作機會。 開發人員可利用集合有效地管理和組織資料,而 IronPDF 可讓您輕鬆建立視覺美觀的 PDF 文件。 IronPDF 和 collections 的結合威力為 C# 應用程式中的動態內容製作提供了可靠且適應性強的解決方案,無論您正在製作哪種文件 - 發票、報告或其他任何文件。

IronPdf 的 $799 Lite 版本包含一年的軟體支援、升級選項以及永久授權。 使用者也有機會在有水印的試用期間,在實際環境中評估產品。 要瞭解 IronPDF 的成本、授權和免費試用的詳細資訊,請造訪 IronPDF 授權資訊。 如需 Iron Software 的詳細資訊,請至 Iron Software 網站

常見問題解答

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

C# 中的集合對於資料儲存和組織是不可或缺的,為開發人員提供了有效處理複雜程式設計挑戰的工具。它們允許動態記憶體分配和資料集的簡易操作。

C# 中的非泛型集合與泛型集合有何差異?

非一般的集合,例如 ArrayListHashtable 是較不安全的類型,可以儲存任何物件類型。通用集合,如 ListDictionary 則透過強制資料類型一致性來提供類型安全性和增強效能。

如何在 C# 中建立一般清單?

C# 中的一般清單可以使用 List 類建立。例如,可以使用 Listnumbers = new List{ 1, 2, 3 }; 建立整數清單。

如何在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字串轉換為 PDF。它也支援將 HTML 檔案和 URL 轉換成 PDF 文件,並保持版面和樣式的完整性。

在 C# 中使用集合的最佳做法有哪些?

在 C# 中使用集合的最佳實務包括:根據您的需求選擇正確的集合類型,例如使用 Dictionary 來處理鍵值對,以及使用 List 來處理有序清單,並在不再需要集合時,透過棄置集合來確保正確的記憶體管理。

集合如何增強 C# 應用程式中的 PDF 創作?

集合可以有效率地組織資料以建立文件。例如,使用 List 來編譯銷售資料,可以方便使用 IronPDF 來產生全面的 PDF 報告,簡化資料管理和呈現。

IronPDF 有哪些授權選項?

IronPdf 提供 Lite License 一年的支援與升級,以及水印試用版的評估。這些選項可讓開發人員在其專案中測試並實作 IronPDF 的功能。

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

您可以使用 NuGet Package Manager,使用 Install-Package IronPdf 命令在 .NET 專案中安裝 IronPDF。或者,您也可以在 NuGet Package Manager 中搜尋「IronPDF」,將它新增到您的專案中。

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

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。