跳過到頁腳內容
.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: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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。