.NET 幫助

C# 資料結構(開發人員的運作方式)

發佈 2024年4月3日
分享:

資料結構 在任何程式語言中,資料結構是軟體開發的關鍵,幫助在應用程式內整齊且有效地存儲和處理資料。資料結構在有效組織和管理資料方面扮演著重要角色。

在 C# 中,像許多程式語言一樣,理解資料結構的使用是創建高效、可擴展和可維護的軟體的基礎。本指南將向您介紹 C# 中資料結構的基礎知識並提供適合初學者的例子。我們還將學習 IronPDF 庫 及其在本文後面的潛在用途。

基本資料結構及其用途

對於任何應用程式來說,資料結構提供了結構化的資料存儲,滿足了各種操作需求。選擇合適的資料結構可以顯著地影響應用程式的性能和記憶體效率。

陣列:資料組織的基礎

陣列是 C# 中最基本和廣泛使用的資料結構之一。它們將相同資料類型的元素存儲在連續的記憶體位置中,允許通過索引高效地訪問元素。陣列在事先已知元素數量且不會改變的情況下非常理想。

int [] numbers = new int [5] {1, 2, 3, 4, 5};
int [] numbers = new int [5] {1, 2, 3, 4, 5};
Dim numbers() As Integer = {1, 2, 3, 4, 5}
VB   C#

通過通過索引訪問元素,陣列使我們可以輕鬆檢索數據,初始項位於索引0。 例如,numbers [0] 會訪問 numbers 陣列的第一個元素,即 1**。

列表:動態數據集合

與陣列不同,C#中的列表提供動態調整大小的功能,適用於元素數量隨時間變化的場景。C# 支持各種數據類型,並通過像列表這樣的數據結構,允許類型安全的存儲。

List<int> numbers = new List<int> {1, 2, 3, 4, 5};
numbers.Add(6); // Adding a new element to the list
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
numbers.Add(6); // Adding a new element to the list
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
numbers.Add(6) ' Adding a new element to the list
VB   C#

列表是多功能的,幫助您自由添加、移除和訪問元素,而不用擔心底層數據的大小。

字典:鍵值關聯

字典以鍵值對的形式存儲關聯,使其成為需要基於唯一鍵訪問值的情況下的理想選擇。這在管理用戶會話、配置或任何需要通過鍵查找的場景中特別有用。

Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages.Add("Bob", 25);
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages.Add("Bob", 25);
Dim ages As New Dictionary(Of String, Integer)()
ages.Add("Alice", 30)
ages.Add("Bob", 25)
VB   C#

在這個例子中,每個人的名字都與他們的年齡相關聯,這樣可以根據名字快速查詢個人的年齡。

堆疊和隊列:管理集合

堆疊採用後進先出 (後進先出) 原則,使其非常適合需要先存取最新添加元素的集合管理,例如在撤銷機制或任務調度系統中。

Stack<string> books = new Stack<string>();
books.Push("Book 1");
books.Push("Book 2");
string lastAddedBook = books.Pop(); // Removes and returns "Book 2"
Stack<string> books = new Stack<string>();
books.Push("Book 1");
books.Push("Book 2");
string lastAddedBook = books.Pop(); // Removes and returns "Book 2"
Dim books As New Stack(Of String)()
books.Push("Book 1")
books.Push("Book 2")
Dim lastAddedBook As String = books.Pop() ' Removes and returns "Book 2"
VB   C#

另一方面,佇列以先進先出方式運作。 (先入先出) 基礎。他們在像是打印任務排程或管理客戶服務請求的情境中很有用。

Queue<string> customers = new Queue<string>();
customers.Enqueue("Customer 1");
customers.Enqueue("Customer 2");
string firstCustomer = customers.Dequeue(); // Removes and returns "Customer 1"
Queue<string> customers = new Queue<string>();
customers.Enqueue("Customer 1");
customers.Enqueue("Customer 2");
string firstCustomer = customers.Dequeue(); // Removes and returns "Customer 1"
Dim customers As New Queue(Of String)()
customers.Enqueue("Customer 1")
customers.Enqueue("Customer 2")
Dim firstCustomer As String = customers.Dequeue() ' Removes and returns "Customer 1"
VB   C#

鏈結串列:自訂資料結構

鏈結串列由包含數據和對序列中下一個節點的引用的節點組成,允許高效的元素插入和移除。它們在需要頻繁操作個別元素的應用程式中特別有用,例如社交媒體應用程式中的聯絡人列表。

public class Node
{
    public int data;
    public Node next;
    public Node(int d) { data = d; next = null; }
}
public class LinkedList
{
    public Node head;
    public void Add(int data)
    {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
    public void Display()
    {
        Node current = head;
        while (current != null)
        {
            Console.WriteLine(current.data);
            current = current.next;
        }
    }
}
public class Node
{
    public int data;
    public Node next;
    public Node(int d) { data = d; next = null; }
}
public class LinkedList
{
    public Node head;
    public void Add(int data)
    {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
    public void Display()
    {
        Node current = head;
        while (current != null)
        {
            Console.WriteLine(current.data);
            current = current.next;
        }
    }
}
Public Class Node
	Public data As Integer
	Public [next] As Node
	Public Sub New(ByVal d As Integer)
		data = d
		[next] = Nothing
	End Sub
End Class
Public Class LinkedList
	Public head As Node
	Public Sub Add(ByVal data As Integer)
		Dim newNode As New Node(data)
		newNode.next = head
		head = newNode
	End Sub
	Public Sub Display()
		Dim current As Node = head
		Do While current IsNot Nothing
			Console.WriteLine(current.data)
			current = current.next
		Loop
	End Sub
End Class
VB   C#

树和图:复杂的数据结构

樹,例如二元樹,以層次方式組織數據,使得搜索、插入和刪除等操作能夠高效地執行。例如,二元樹在實現像二元搜索和廣度優先搜索這樣的演算法中是基礎性的。

圖,由節點组成 (頂點) 和邊緣 (連接)用來表示網絡,例如社交圖譜或交通地圖。樹和圖都是在解決涉及層次數據或網絡關係的複雜問題中非常重要的。

選擇合適的資料結構

資料結構的選擇對於應用程式的效率和性能有著顯著的影響。這不僅僅是選擇任何資料結構的問題;而是要辨認出適合你特定任務或演算法需求的正確資料結構。

這個選擇受多種因素的影響,包括你需要最常執行的操作類型。 (例如搜尋、插入或刪除資料)這些操作的速度和記憶體使用量。

選擇資料結構的標準

  1. 操作複雜度:考慮您需要多快完成常見操作。例如,如果需要頻繁根據鍵訪問元素,哈希表可能是理想選擇。 (在 C# 中實現為 Dictionary) 可能是最有效的選擇。

  2. 記憶體效率:評估資料結構消耗的記憶體量,特別是當你要處理大量資料時。像鏈結串列結構在某些操作中可能比陣列更有效率,因為它們不會為未使用的元素分配記憶體。

  3. 實作簡便性:某些資料結構可能為你的特定應用提供更簡單的實作。例如,如果你需要經常從一端添加和移除元素,堆疊佇列可能比鏈結串列更容易使用和理解。

  4. 資料大小和擴展性:考慮你的資料大小是否是固定的或動態的。陣列適合固定大小的資料集合,而列表或鏈結串列更適合需要動態增減的資料集合。

IronPDF 介紹:C# PDF 庫

C# 資料結構(開發人員如何使用):圖 1

IronPDF 是一個為開發人員設計的綜合性庫,用於在.NET應用程式中創建、編輯和提取PDF內容。它提供了一種簡單的方法來轉換 HTML轉PDF 幫助製作像素完美的PDF。

憑藉其多樣化的功能,開發人員可以輕鬆實現複雜的PDF功能。IronPDF簡化了PDF操作的過程,並在C#項目中增添了高效的文件管理功能。

範例:從數據清單生成 PDF

假設您需要從客戶姓名和電子郵件列表生成報告。首先,您將數據結構化為一個自定義類別 CustomerList,然後使用 IronPDF 從該列表創建一個 PDF 文件。

using IronPdf;
using System.Collections.Generic;
public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // Create a list of customers
        List<Customer> customers = new List<Customer>
        {
            new Customer { Name = "Alice Johnson", Email = "alice@example.com" },
            new Customer { Name = "Bob Smith", Email = "bob@example.com" }
        };
        // Initialize the HTML to PDF converter
        var renderer = new ChromePdfRenderer();
        // Generate HTML content from the list of customers
        var htmlContent = "<h1>Customer List</h1><ul>";
        foreach (var customer in customers)
        {
            htmlContent += $"<li>{customer.Name} - {customer.Email}</li>";
        }
        htmlContent += "</ul>";
        // Convert HTML to PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF document
        pdf.SaveAs("CustomerList.pdf");
    }
}
using IronPdf;
using System.Collections.Generic;
public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }
}
class Program
{
    static void Main(string [] args)
    {
        License.LicenseKey = "License-Key";
        // Create a list of customers
        List<Customer> customers = new List<Customer>
        {
            new Customer { Name = "Alice Johnson", Email = "alice@example.com" },
            new Customer { Name = "Bob Smith", Email = "bob@example.com" }
        };
        // Initialize the HTML to PDF converter
        var renderer = new ChromePdfRenderer();
        // Generate HTML content from the list of customers
        var htmlContent = "<h1>Customer List</h1><ul>";
        foreach (var customer in customers)
        {
            htmlContent += $"<li>{customer.Name} - {customer.Email}</li>";
        }
        htmlContent += "</ul>";
        // Convert HTML to PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF document
        pdf.SaveAs("CustomerList.pdf");
    }
}
Imports IronPdf
Imports System.Collections.Generic
Public Class Customer
	Public Property Name() As String
	Public Property Email() As String
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		' Create a list of customers
		Dim customers As New List(Of Customer) From {
			New Customer With {
				.Name = "Alice Johnson",
				.Email = "alice@example.com"
			},
			New Customer With {
				.Name = "Bob Smith",
				.Email = "bob@example.com"
			}
		}
		' Initialize the HTML to PDF converter
		Dim renderer = New ChromePdfRenderer()
		' Generate HTML content from the list of customers
		Dim htmlContent = "<h1>Customer List</h1><ul>"
		For Each customer In customers
			htmlContent &= $"<li>{customer.Name} - {customer.Email}</li>"
		Next customer
		htmlContent &= "</ul>"
		' Convert HTML to PDF
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF document
		pdf.SaveAs("CustomerList.pdf")
	End Sub
End Class
VB   C#

在這個例子中,IronPDF 與 List 密切合作**資料結構,展示該庫將結構化的C#資料轉換成專業品質的PDF文件的能力。

C# 資料結構(開發人員如何使用):圖2

結論

C# 資料結構(對開發者的工作方式):圖 3

總結而言,選擇最佳的資料結構是軟體開發的關鍵步驟。對於開發人員來說,理解這些結構及其實際應用是至關重要的。此外,對於那些在 .NET 專案中尋找 PDF 生成和操作的人來說,IronPDF 提供了一個強大的解決方案,具有 免費試用 從 $749 開始,提供適合各種開發需求的一系列功能。

< 上一頁
C# 絕對值(開發人員如何使用)
下一個 >
C# 中的日期時間對象(開發人員如何使用)

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

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