跳過到頁腳內容
.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字典<TKey, TValue>, 隊列以及 Stack以下是一些常用的詞彙。 這些集合是當代 C# 開發的首選,因為它們提供更好的效能和編譯時的類型驗證。

主要 C# 集合類型

1. 列表

列表是一種動態數組,可以方便快速地插入和刪除元素。班級。 由於它提供篩選、搜尋和操作元件的方式,因此對於需要可調整大小的集合的情況而言,它是一個彈性的選擇。

// 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)兩種收集方式分別由通用佇列實現。通用堆疊課程。 這些工具可用於根據應用程式的需求,以特定順序管理項目。

// 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)表示無序集合中排列的唯一元素。班級。 它提供了執行集合運算的有效方法,例如差集、合集和交集。

// 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 (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 的介面之前,瞭解集合在資料結構和組織中扮演的角色至關重要。 開發人員可以透過使用集合,以有組織的方式儲存、擷取和修改事物群組。 有如此多的不同類型可供選擇,例如列表字典<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# 中創建泛型列表?

可以使用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' 來將其添加到您的項目中。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我