.NET 幫助

C# 集合(開發人員如何使用)

發佈 2024年3月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# 版本引入了泛型集合,以克服非泛型集合的缺點。它們在編譯期間提供了類型安全性,讓開發人員處理嚴格類型的數據。泛型集合類別 List,詞典<TKey, TValue>,隊列,和Stack是一些經常使用的選擇。這些集合是當代C#開發的首選,因為它們提供了更好的性能和編譯時類型驗證。

主要的C# 集合类型

1. 列表

List 是一種動態陣列,方便快速添加和移除元素。class。這是一個靈活的選項,適用於需要可調整大小的集合的情況,因為它提供了篩選、搜索和操作組件的方法。

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# 集合(它如何為開發者運作):圖 1 - IronPDF 網站頁面

名為的 C# 庫 IronPDF 讓在 .NET 應用程式中創建、編輯和顯示 PDF 文件變得簡單。 它提供多種授權選擇、跨平台相容性、高品質渲染和 HTML 轉 PDF 轉換。IronPDF 的用戶友好型 API 使處理 PDF 更加簡便,這使其對於 C# 開發者來說是一個有用的工具。

IronPDF 的傑出功能是其 HTML 轉 PDF 功能,維持所有的佈局和樣式。它從網頁內容生成PDF,使其非常適合報告、發票和文件。HTML文件、網址和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文本生成PDF文檔,包含CSS和JavaScript。這對於已經熟悉網頁開發工具並希望使用HTML和CSS生成PDF的人來說非常有幫助。
  • PDF生成和操作:該庫提供了程式化從零開始創建PDF文檔的能力。此外,它還便於編輯已有的PDF,可以執行如提取文本、添加水印、拆分PDF等操作。
  • 卓越的渲染:IronPDF使用渲染引擎來生成最高品質的PDF輸出,保證最終文檔保持清晰度和視覺完整性。
  • 跨平台兼容性:IronPDF被設計為可與.NET Core和.NET Framework一起使用,因此可以在各種應用程序和平台上使用。
  • 性能優化:即使在處理大型或複雜的PDF文檔時,該庫也被設計為提供高效的PDF生成和渲染。

要了解有關IronPDF文檔的更多信息,請參見 這裡.

安裝 IronPDF

首先使用套件管理器控制台或 NuGet 套件管理器安裝 IronPDF 庫:

Install-Package IronPdf

C# 集合(適用於開發人員):圖 2 - 使用套件管理器控制台安裝 IronPDF

使用 NuGet 套件管理器來搜尋 "IronPDF" 套件也是一個選擇。我們可以從這份列表中選擇並下載與 IronPDF 相關的所有 NuGet 套件中的必要套件。

C# 集合 (開發者如何使用):圖 3 - 使用 NuGet 套件管理器安裝 IronPDF

使用 IronPDF 創建包含集合的文檔

在進入使用 IronPDF 的介面之前,了解集合在資料結構與組織中所扮演的角色是至關重要的。開發者可以使用集合來有序地存儲、檢索和修改物件群組。有很多不同類型的集合可供使用,例如 List,詞典<TKey, TValue>,和 HashSet,開發人員可以選擇最符合其需求的集合。

想像一下,您需要製作一個包含銷售交易清單的報告。可以使用清單(List)有效地組織數據。,作為進一步處理和顯示的基礎。

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# 集合(對開發人員的運作方式):圖 4 - 由前面的代碼生成的 PDF

上面的螢幕顯示了由上述代碼生成的輸出。要了解更多關於該代碼的內容,請參閱 這裡.

結論

通過將集合與IronPDF相結合,可以實現動態文檔製作的豐富機會。開發人員可以利用集合有效地管理和組織數據,而IronPDF則使創建視覺上美觀的PDF文檔變得容易。無論您正在生成哪種類型的文檔——發票、報告或其他任何文檔,IronPDF和集合的組合力量為C#應用中的動態內容生產提供了一個可靠且靈活的解決方案。

IronPDF的 $749 Lite版包括一年的軟件支持、升級選項和永久許可。用戶還可以在帶水印的試用期內在現實環境中評估產品。欲了解更多關於IronPDF的費用、許可和免費試用,請訪問許可。 頁面如需有關 Iron Software 的更多資訊,請前往此 網站.

< 上一頁
MSTest C#(它如何為開發人員工作)
下一個 >
C# Null 條件運算子(開發人員如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >