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
在上面的範例中,我們建立了一個空列表,並使用 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
此代碼可達到與前一範例相同的結果,但形式更精簡。 集合初始化器可讓您在單一語句中初始化具有值的清單,使您的程式碼更具可讀性。
物件初始化器和清單初始化
物件初始化器語法是另一種初始化清單的方式,主要是在處理自訂物件時使用。 以下是一個物件初始化器如何使用清單的範例:
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
}
}
在這個範例中,我們使用物件初始化器建立了 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
Dim fruits As New List(Of String)(10) ' Initial size of 10
這會建立一個初始容量為 10 的空清單。雖然它沒有增加元素,但它分配了足夠的記憶體,在不調整內部陣列大小的情況下,最多可容納 10 個元素。
從陣列初始化清單
您也可以使用接受參數的列表建構函數從現有數組初始化列表。 當您有一個陣列,並希望將其轉換成列表以提高彈性時,這將非常有用。
// 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)
這裡建立了一個新陣列,然後用它來初始化一個列表。這會將陣列轉換為列表。任何物件,包括陣列,都可以傳遞給列表建構函式進行初始化。
使用 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)
在這個例子中,我們從一個包含兩個元素的清單開始,並使用 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
}
}
此技術可在單一語句中建立並初始化物件清單,使程式碼簡潔且易於閱讀。
使用擴充方法進行清單初始化
您也可以實作擴充方法,以自訂方式初始化清單。 擴充方法提供一種機制,在不改變原有結構的情況下,以新的功能改善現有類型。
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");
Imports System.Collections.Generic
Public Module ListExtensions
<System.Runtime.CompilerServices.Extension>
Public Function InitializeWith(Of T)(list As List(Of T), ParamArray elements As T()) As List(Of T)
list.AddRange(elements)
Return list
End Function
End Module
' Usage
Dim fruits As List(Of String) = New List(Of String)().InitializeWith("Apple", "Banana", "Cherry")
在這裡,我們定義了一個擴展方法,InitializeWith,該方法向列表中添加元素並返回列表本身。 這可讓您鏈結清單的初始化和人口。
IronPDF:C# PDF 函式庫

如果您有一張清單,例如水果清單,您可以快速將它變成 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

這段程式碼初始化一個列表,從中建立 HTML 表格,並使用 IronPDF 建立 PDF 檔案。這是從您的資料集合產生 PDF 的簡單直接方式。
結論
。
C# 中的列表初始化是每位軟體工程師都應該掌握的基本概念。 無論您是處理簡單的字串清單或複雜的物件清單,C# 都提供了多種方法來有效率地初始化和填充清單。 從基本初始化到物件與集合初始化器,這些技術可協助您撰寫乾淨、簡潔且可維護的程式碼。
IronPDF 提供 免費試用,讓您無需初始投資即可試用產品。 當您確信它滿足您的需求時,許可證起價為 $999。
常見問題解答
在 C# 中初始化清單的基本方法有哪些?
在 C# 中,您可以透過建立 List 類別的執行個體來初始化清單,其中 T 是元素類型。例如,List 是初始化清單的基本方式。
集合初始化器語法如何改進 C# 中的清單初始化?
集合初始化器語法允許您在建立清單時直接填入資料,使程式碼更加簡潔。例如:List。
初始化清單時,物件初始化器語法的目的是什麼?
物件初始化器語法對於使用自訂物件初始化清單很有幫助,允許在建立清單時設置屬性值。例如:new Person { Name = 'John', Age = 30 }; 在清單中。
您可以為清單設置初始容量嗎?為什麼這很有幫助呢?
是的,為清單設置初始容量可以透過減少清單增長時的記憶體重新分配來提高性能。例如:List。
如何從現有陣列初始化 C# 中的清單?
您可以使用接受 IEnumerable 的清單建構函式從陣列初始化清單。例如:List。
AddRange 方法在清單初始化中起什麼作用?
AddRange 方法一次將多個元素從集合添加到清單中,透過最小化重新分配來優化性能。例如:fruits.AddRange(moreFruits);。
如何使用初始化器在清單中初始化自訂物件?
可以使用物件和集合初始化器的組合在清單中初始化自訂物件,實現清單建立的單一運算式。例如:new List。
擴充方法是什麼,它們與清單初始化有什麼關係?
擴充方法允許為現有類型添加新功能。例如,可以編寫像 InitializeWith 之類的擴充方法來簡化清單的初始化和填充。
如何將清單轉換為 C# 中的 PDF?
使用 IronPDF,您可以將清單轉換為 HTML 表格並將其渲染為 PDF,簡化從資料集合生成 PDF 的過程。
是否有免費試用版可用於從資料集合生成 PDF?
是的,IronPDF 提供免費試用,允許用戶在不進行初始購買的情況下測試其 PDF 生成功能。



