跳至页脚内容
.NET 帮助

C# 初始化列表(开发者用法)

列表是System.Collections.Generic命名空间的一部分,适用于处理数据集合。 C#中的列表是动态的,这意味着其大小可以在运行时更改。在许多软件工程场景中,这是非常有帮助的,其中元素数量事先未知。 让我们深入探讨在C#中初始化列表的不同方式。 我们将介绍基础技术、对象初始化语法、集合初始化器以及IronPDF库

基本列表初始化

要初始化列表,请先创建List<T>类的实例,其中T是列表中元素的类型。最常见的类型是string,但你可以使用任何类型。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize an empty list
        List<string> fruits = new List<string>();

        // Adding elements to the list
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        // Display the list
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize an empty list
        List<string> fruits = new List<string>();

        // Adding elements to the list
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        // Display the list
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Imports System
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		' Initialize an empty list
		Dim fruits As New List(Of String)()

		' Adding elements to the list
		fruits.Add("Apple")
		fruits.Add("Banana")
		fruits.Add("Cherry")

		' Display the list
		For Each fruit In fruits
			Console.WriteLine(fruit)
		Next fruit
	End Sub
End Class
$vbLabelText   $csharpLabel

在上面的示例中,我们创建了一个空列表,并使用Add方法添加元素。 List<string>表示一个字符串列表,我们使用Add方法为其添加值。

使用集合初始化器语法

C#提供了一种更简洁的方法,可以使用集合初始化器语法初始化列表。 这允许您在创建时直接填充列表,而无需重复调用Add方法。

public void InitializeList()
{
    List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
public void InitializeList()
{
    List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
Public Sub InitializeList()
	Dim fruits As New List(Of String) From {"Apple", "Banana", "Cherry"}
End Sub
$vbLabelText   $csharpLabel

这段代码实现了与前面的示例相同的结果,但形式更为简洁。 集合初始化器允许您在一个语句中用值初始化列表,提高了代码的可读性。

对象初始化器和列表初始化

对象初始化器语法是另一种初始化列表的方法,主要用于处理自定义对象。 这是对象初始化器如何与列表配合使用的示例:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Jack", Age = 35 }
};
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Jack", Age = 35 }
};
Friend Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class

Private people As New List(Of Person) From {
	New Person With {
		.Name = "John",
		.Age = 30
	},
	New Person With {
		.Name = "Jane",
		.Age = 25
	},
	New Person With {
		.Name = "Jack",
		.Age = 35
	}
}
$vbLabelText   $csharpLabel

在这个示例中,我们使用对象初始化器创建了一个Person对象列表。 Person类具有两个属性:NameAge,在创建列表时被明确赋予值。

创建具有初始大小的列表

虽然列表的大小是动态的,但如果您大致知道列表将包含的元素数量,则可以指定初始容量。 这可以通过减少内存重新分配次数来提高性能。

List<string> fruits = new List<string>(10); // Initial size of 10
List<string> fruits = new List<string>(10); // Initial size of 10
Dim fruits As New List(Of String)(10) ' Initial size of 10
$vbLabelText   $csharpLabel

这创建了一个初始容量为10的空列表。虽然没有添加元素,但已经分配了足够的内存以容纳最多10个元素而无需调整内部数组大小。

从数组初始化列表

您还可以使用接受IEnumerable<T>参数的列表构造函数,从现有数组初始化列表。 当您有一个数组并希望将其转换为列表以获得灵活性时,这非常有用。

// New String array of fruit
string[] fruitArray = { "Apple", "Banana", "Cherry" };
List<string> fruits = new List<string>(fruitArray);
// New String array of fruit
string[] fruitArray = { "Apple", "Banana", "Cherry" };
List<string> fruits = new List<string>(fruitArray);
' New String array of fruit
Dim fruitArray() As String = { "Apple", "Banana", "Cherry" }
Dim fruits As New List(Of String)(fruitArray)
$vbLabelText   $csharpLabel

在这里,创建一个新数组,然后用它初始化列表。这将fruitArray数组转换为列表。任何IEnumerable<T>,包括数组,都可以传递给列表构造函数进行初始化。

使用AddRange方法

如果您有一个现有项目集合,可以使用AddRange方法将多个元素一起添加到列表中。

List<string> fruits = new List<string> { "Apple", "Banana" };
string[] moreFruits = { "Cherry", "Date", "Elderberry" };
fruits.AddRange(moreFruits);
List<string> fruits = new List<string> { "Apple", "Banana" };
string[] moreFruits = { "Cherry", "Date", "Elderberry" };
fruits.AddRange(moreFruits);
Dim fruits As New List(Of String) From {"Apple", "Banana"}
Dim moreFruits() As String = { "Cherry", "Date", "Elderberry" }
fruits.AddRange(moreFruits)
$vbLabelText   $csharpLabel

在这个示例中,我们从包含两个元素的列表开始,并使用AddRange从数组中添加多个新项目。 这种方法可以通过批量添加元素而提高性能,因为它减少了多次重新分配的需要。

用自定义对象初始化列表

在初始化自定义对象的列表时,可以将对象初始化器与集合初始化器结合使用,在一个表达式中创建复杂的数据结构。

List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 28 },
    new Person { Name = "Bob", Age = 32 },
    new Person { Name = "Charlie", Age = 40 }
};
List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 28 },
    new Person { Name = "Bob", Age = 32 },
    new Person { Name = "Charlie", Age = 40 }
};
Dim people As New List(Of Person) From {
	New Person With {
		.Name = "Alice",
		.Age = 28
	},
	New Person With {
		.Name = "Bob",
		.Age = 32
	},
	New Person With {
		.Name = "Charlie",
		.Age = 40
	}
}
$vbLabelText   $csharpLabel

这种技术允许在一个语句中创建和初始化对象列表,使代码简洁且易于阅读。

使用扩展方法初始化列表

您还可以实现扩展方法,以自定义方式初始化列表。 扩展方法提供了一种机制,可以在不改变原结构的情况下为现有类型增加新功能。

public static class ListExtensions
{
    public static List<T> InitializeWith<T>(this List<T> list, params T[] elements)
    {
        list.AddRange(elements);
        return list;
    }
}

// Usage
List<string> fruits = new List<string>().InitializeWith("Apple", "Banana", "Cherry");
public static class ListExtensions
{
    public static List<T> InitializeWith<T>(this List<T> list, params T[] elements)
    {
        list.AddRange(elements);
        return list;
    }
}

// Usage
List<string> fruits = new List<string>().InitializeWith("Apple", "Banana", "Cherry");
Public Module ListExtensions
	<System.Runtime.CompilerServices.Extension> _
	Public Function InitializeWith(Of T)(ByVal list As List(Of T), ParamArray ByVal elements() As T) As List(Of T)
		list.AddRange(elements)
		Return list
	End Function
End Module

' Usage
Private fruits As List(Of String) = (New List(Of String)()).InitializeWith("Apple", "Banana", "Cherry")
$vbLabelText   $csharpLabel

在这里,我们定义了一个扩展方法InitializeWith,它向列表添加元素并返回列表本身。 这允许您链式调用列表的初始化和填充。

探索 IronPDF 用于 PDF 管理 是一个为使用 C# 编程语言的开发人员提供的工具,允许他们在其应用程序内部直接创建、读取和编辑 PDF 文档。

C#初始化列表(开发人员如何使用):图1 - IronPDF:C# PDF库

If you have a list, like a list of fruits, you can quickly turn it into an HTML table and render it as a PDF using IronPDF, all in just a few lines of code. 过程很简便:初始化您的列表,转换为HTML,然后让IronPDF生成PDF。 以下是一个例子:

using IronPdf;
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        // Initialize a list of strings representing data
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        // Convert the list to an HTML table
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.Append("<table border='1'><tr><th>Fruit Name</th></tr>");
        foreach (var fruit in fruits)
        {
            htmlContent.Append($"<tr><td>{fruit}</td></tr>");
        }
        htmlContent.Append("</table>");

        // Render the HTML to PDF using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent.ToString());

        // Save the PDF to a file
        PDF.SaveAs("FruitsList.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        // Initialize a list of strings representing data
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        // Convert the list to an HTML table
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.Append("<table border='1'><tr><th>Fruit Name</th></tr>");
        foreach (var fruit in fruits)
        {
            htmlContent.Append($"<tr><td>{fruit}</td></tr>");
        }
        htmlContent.Append("</table>");

        // Render the HTML to PDF using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent.ToString());

        // Save the PDF to a file
        PDF.SaveAs("FruitsList.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Text

Friend Class Program
	Shared Sub Main()
		' Initialize a list of strings representing data
		Dim fruits As New List(Of String) From {"Apple", "Banana", "Cherry"}

		' Convert the list to an HTML table
		Dim htmlContent As New StringBuilder()
		htmlContent.Append("<table border='1'><tr><th>Fruit Name</th></tr>")
		For Each fruit In fruits
			htmlContent.Append($"<tr><td>{fruit}</td></tr>")
		Next fruit
		htmlContent.Append("</table>")

		' Render the HTML to PDF using IronPDF
		Dim Renderer = New ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent.ToString())

		' Save the PDF to a file
		PDF.SaveAs("FruitsList.pdf")
		Console.WriteLine("PDF generated successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

C#初始化列表(开发人员如何使用):图2 - 示例输出

此代码初始化列表,从中创建HTML表格,并使用IronPDF创建PDF文件。 这是一种从数据集合生成PDF的简单直接的方法。

结论

C#初始化列表(开发人员如何使用):图3 - IronPDF许可页面

在C#中,列表初始化是每个软件工程师都应掌握的基本概念。 无论您是在处理简单的字符串列表还是复杂的对象列表,C#提供了几种方法可以有效地初始化和填充列表。 从基础初始化到对象和集合初始化器,这些技术帮助您编写简洁、清晰和可维护的代码。

IronPDF提供免费试用,让您无需初始投资即可试用产品。 当您确信它满足您的需求时,$799起的许可证可供购买。

常见问题解答

在C#中有哪些基本方法可以初始化列表?

在C#中,你可以通过创建List<T>类的实例来初始化列表,其中T是元素类型。例如,List<string> fruits = new List<string>();是初始化列表的基本方式。

集合初始化器语法如何改进C#中的列表初始化?

集合初始化器语法允许您在创建列表时直接填充,从而使代码更简洁。例如:List<string> fruits = new List<string> { 'Apple', 'Banana', 'Cherry' };

在初始化列表时,对象初始化器语法的目的是什么?

对象初始化器语法有利于初始化具有自定义对象的列表,允许在创建列表时设置属性值。例如:在列表中使用new Person { Name = 'John', Age = 30 };

你可以为列表设置初始容量吗?为什么这有帮助?

是的,设置列表的初始容量可以提高性能,因为随着列表增长可以减少内存重新分配的需要。例如:List<string> fruits = new List<string>(10);

如何在C#中从现有数组初始化列表?

你可以使用接受IEnumerable<T>的列表构造函数从数组初始化列表。例如:List<string> fruits = new List<string>(fruitArray);

AddRange方法在列表初始化中起什么作用?

AddRange方法一次性将多个元素从集合添加到列表中,通过最小化重新分配来优化性能。例如:fruits.AddRange(moreFruits);

如何使用初始化器在列表中初始化自定义对象?

可以结合使用对象和集合初始化器在列表中初始化自定义对象,这样就能通过单个表达式来创建列表。例如:new List<Person> { new Person { Name = 'Alice', Age = 28 } };

扩展方法是什么以及它们如何与列表初始化相关?

扩展方法允许为现有类型添加新功能。例如,可以编写类似InitializeWith的扩展方法来简化列表的初始化和填充。

如何在C#中将列表转换为PDF?

使用IronPDF,可以将列表转换为HTML表格并将其渲染为PDF,以简化从数据集合生成PDF的过程。

是否有免费的试用版可用于从数据集合生成PDF?

是的,IronPDF提供一个免费试用版,允许用户在未进行初始购买的情况下测试其数据集合的PDF生成功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。