.NET 帮助

C# 数据结构(开发人员如何使用)

发布 2024年四月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。例如,数字 [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# 中以字典的形式实现) 可能是最有效的选择。

  2. 内存效率:评估数据结构消耗多少内存,尤其是在处理大量数据时。在某些操作中,链接列表等结构比数组更节省内存,因为它们不会为未使用的元素分配内存。

  3. 易于实现:某些数据结构可能会为你的特定用例提供更直接的实现方式。例如,如果您需要经常只从一端添加和删除元素,那么队列可能比链表更易于使用和理解。

  4. 数据大小和可扩展性:考虑数据大小是固定的还是动态的。数组是固定大小数据集合的理想选择,而列表或链表则更适合需要动态增长或收缩的数据集合。

IronPDF 简介:C# PDF Library

C# 数据结构(如何为开发人员工作):图 1

IronPDF 是一个综合库,专为开发人员在 .NET 应用程序中创建、编辑和提取 PDF 内容而设计。它提供了一种直接转换 HTML 转 PDF 它有助于创建像素完美的 PDF 文件。

凭借其丰富的功能,开发人员可以轻松实现复杂的 PDF 功能。IronPDF 简化了 PDF 操作过程,并在 C# 项目中增加了高效的文档管理功能。

示例:从数据列表生成 PDF

假设您需要根据客户姓名和电子邮件列表生成一份报告。首先,您需要在自定义类客户列表中构建数据结构,然后使用 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.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >