跳過到頁腳內容
.NET幫助

C# 初始化列表 (如何為開發人員運作)

清單是 System.Collections.Generic 命名空間的一部分,是處理資料集合的通用工具。 C# 中的列表是動態的,這表示它們的大小可以在執行時改變。這種靈活性在許多不知道元素數量的軟體工程情境中非常有用。 讓我們深入了解在 C# 中初始化清單的不同方式。 我們將介紹基本技術、物件初始化器語法、集合初始化器,以及 IronPdf 函式庫

基本清單初始化

要初始化一個 list,首先要建立一個 List<T> 類的實體,其中 T 是 list 中元素的類型。最常見的類型是 字串,但您也可以使用任何類型。

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> 參數的 list 建構器從現有的陣列初始化一個 list。 當您有一個陣列,並希望將其轉換成列表以提高彈性時,這將非常有用。

// 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

在這裡,會建立一個新的陣列,然後用來初始化一個 list。這會將 fruitArray 陣列轉換成一個 list。任何IEnumerable<T>,包括陣列,都可以傳給 list 建構器來初始化。

使用 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# Initialize List (How It Works For Developers):圖 1 - IronPDF:C# PDF Library

如果您有一張清單,例如水果清單,您可以快速將它變成 HTML表格,並使用 IronPDF 將它渲染成 PDF,這一切只需要幾行程式碼。 過程簡單直接:初始化您的清單,將其轉換為 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# Initialize List (How It Works For Developers):圖 2 - 輸出範例

這段程式碼初始化一個列表,從中建立 HTML 表格,並使用 IronPDF 建立 PDF 檔案。這是從您的資料集合產生 PDF 的簡單直接方式。

結論

C# Initialize List (How It Works For Developers):圖 3 - IronPDF 授權頁面

C# 中的列表初始化是每位軟體工程師都應該掌握的基本概念。 無論您是處理簡單的字串清單或複雜的物件清單,C# 都提供了多種方法來有效率地初始化和填充清單。 從基本初始化到物件與集合初始化器,這些技術可協助您撰寫乾淨、簡潔且可維護的程式碼。

IronPdf 提供 免費試用,讓您無需初始投資即可試用產品。 當您確信它能滿足您的需求時,可提供 $799 起的授權。

常見問題解答

C# 中初始化 list 的基本方法有哪些?

在 C# 中,您可以透過建立 List<T> 類的實體來初始化一個 list,其中 T 是元素的類型。例如,List<string> fruits = new List<string>();是初始化 list 的基本方法。

集合初始化器語法如何改善 C# 中的清單初始化?

集合初始化器語法允許您在建立清單時直接填充清單,使程式碼更為簡潔。例如List<string> fruits = new List<string> { 'Apple', 'Banana', 'Cherry' };

初始化清單時,物件初始化器語法的目的是什麼?

物件初始化器語法有利於使用自訂物件初始化清單,允許在建立清單時設定屬性值。例如new Person { Name = 'John', Age = 30 };在清單中。

您可以設定列表的初始容量嗎?為什麼這會有幫助?

是的,為清單設定初始容量可以減少清單成長時記憶體重新分配的需求,從而改善效能。範例:List<string> fruits = new List<string>(10);

在 C# 中,如何從現有的陣列初始化一個 list?

您可以使用接受 IEnumerable<T> 的 list 建構器從陣列初始化一個 list。範例:List<string> fruits = new List<string>(fruitArray);

AddRange 方法在清單初始化中扮演什麼角色?

AddRange 方法一次將集合中的多個元素加入清單中,藉由最小化重新分配來最佳化效能。範例fruits.AddRange(moreFruits);

如何使用初始化器在清單中初始化自訂物件?

自訂物件可以使用物件初始化器和集合初始化器的組合在清單中初始化,使單一表達式就能建立清單。範例new List<Person> { new Person { Name = 'Alice', Age = 28 };。};.

什麼是延伸方法,它們與清單初始化有何關聯?

擴充方法允許在現有的類型中加入新的功能。舉例來說,像 InitializeWith 這樣的擴充方法可以用來簡化 list 的初始化和填充。

如何在 C# 中將清單轉換為 PDF?

使用 IronPDF,您可以將列表轉換為 HTML 表格,並將其渲染為 PDF,從而簡化 C# 中從資料集合生成 PDF 的過程。

從資料集合產生 PDF 是否有免費試用版本?

是的,IronPDF 提供免費試用版,允許使用者測試其從資料集合生成 PDF 的功能,而無需初次購買。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。