.NET 幫助

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

喬迪·巴迪亞
喬迪·巴迪亞
2024年10月24日
分享:

清單是的一部分System.Collections.Generic命名空间和在处理数据集合方面非常灵活。 在 C# 中,列表是動態的,這意味著它們的大小可以在運行時改變。這種靈活性在許多軟體工程場景中非常有用,特別是當元素數量事先未知時。 讓我們深入探討在 C# 中初始化列表的不同方法。 我們將介紹基本技術、物件初始化語法、集合初始化器,以及IronPDF 庫.

基本列表初始化

若要初始化列表,首先創建列表的實例。類別,其中 T 是列表中元素的類型。最常見的類型是字串,但您可以使用任何類型。

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);
        }
    }
}

在上面的範例中,我們創建了一個空列表並使用 Add 方法添加元素。 清單代表一個字串列表,我們使用 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" };
}

這段程式碼實現了與前一個範例相同的結果,但形式更加精簡。 集合初始化器允許您在單一語句中使用值初始化列表,使您的程式碼更具可讀性。

物件初始化和列表初始化

物件初始化語法是初始化列表的另一種方式,主要用於處理自訂物件時。 以下是物件初始化器如何與列表一起運作的範例:

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 }
};

在此範例中,我們使用物件初始化器建立一個 Person 物件的列表。 Person 類別有兩個屬性:Name 和 Age,這些屬性在清單建立時被明確指定了值。

創建具有初始大小的列表

雖然列表的大小是動態的,但如果您大致知道列表將包含多少元素,可以指定一個初始容量。 這可以透過減少記憶體重新分配的次數來提高效能。

List<string> fruits = new List<string>(10); // Initial size of 10
List<string> fruits = new List<string>(10); // Initial size of 10

這會建立一個初始容量為 10 的空列表。雖然它不會添加元素,但會分配足夠的記憶體以容納最多 10 個元素而不重新調整內部陣列的大小。

從陣列初始化清單

您也可以使用接受 IEnumerable 的列表構造函數從現有陣列初始化列表。參數。 這在您有一個數組並想將其轉換為列表以提高靈活性時很有用。

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

在這裡,首先創建了一個新的數組,然後用它來初始化一個列表。這將 fruitArray 數組轉換為一個列表。任何 IEnumerable,包括陣列,可以傳遞給清單構造函數進行初始化。

使用 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);

在此範例中,我們從一個包含兩個元素的清單開始,並使用 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 }
};

此技術允許在單一語句中創建並初始化物件列表,使代碼簡潔且易於閱讀。

使用擴充方法進行清單初始化

您也可以實作一個擴展方法,以自定的方式初始化清單。 擴充方法提供了一種機制,可以在不改變原始結構的情況下提高現有類型的新功能。

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");

在此,我們定義了一個擴充方法 InitializeWith,該方法會將元素添加到列表中並返回列表本身。 這允許您連鎖列表的初始化和填充。

IronPDF:C# PDF 庫

C# 初始化列表(開發者運作方式):圖 1 - IronPDF:C# PDF 庫

如果您有一個清單,例如一個水果清單,您可以快速將它轉變成一個將 HTML 表格渲染成 PDFusingIronPDF,只需幾行代碼即可完成。 流程很簡單:初始化您的列表,將其轉換為 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.");
    }
}

C# 初始化列表(開發者如何操作):圖 2 - 範例輸出

此代碼首先初始化一個清單,然後從中創建一個 HTML 表格,並使用 IronPDF 來創建 PDF 檔案。這是一種從資料集合中生成 PDF 的簡單直接的方法。

結論

C# 初始化清單 (開發人員如何使用): 圖 3 - IronPDF 許可頁面

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

IronPDF 提供一個免費試用讓您在不進行初期投資的情況下嘗試該產品。 當您確信它符合您的需求時,許可證的起價為 $749。

喬迪·巴迪亞
軟體工程師
Jordi 最擅長 Python、C# 和 C++,當他不在 Iron Software 發揮技能時,他會進行遊戲編程。他負責產品測試、產品開發和研究,為持續產品改進增添了巨大的價值。多樣化的經驗使他感到挑戰和投入,他說這是與 Iron Software 合作的最喜歡的方面之一。Jordi 在佛羅里達州邁阿密長大,並在佛羅里達大學學習計算機科學和統計學。
< 上一頁
C# 命名規範(開發者如何使用)
下一個 >
FileStream C#(對開發人員的工作方式)