跳至頁尾內容
.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);
        }
    }
}
$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" };
}
$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 }
};
$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
$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);
$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);
$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 }
};
$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");
$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.");
    }
}
$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#中初始化列表的基本方法有哪些?

在 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,從而簡化在 C# 中從資料集產生 PDF 的過程。

是否有免費試用版可以從資料集中產生 PDF 檔案?

是的,IronPDF 提供免費試用,使用者無需預先購買即可測試其從資料集產生 PDF 的功能。

Jacob Mellor,Team Iron 首席技術官
首席技術長

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。