C# 初始化列表 (如何為開發人員運作)
列表是System.Collections.Generic命名空間的一部分,對於處理資料集合非常實用。 C#中的列表是動態的,這意味著它們的大小可以在運行時改變。這種靈活性在許多軟體工程情境中非常有用,尤其當元素數量事先不確定時。 讓我們深入探討在C#中初始化列表的不同方法。 我們將涵蓋基本技術、物件初始化器語法、集合初始化器和IronPDF程式庫。
基本列表初始化
要初始化一個列表,可以通過建立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方法新增元素。 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物件的列表。 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個元素,而無需調整內部陣列的大小。
從陣列初始化列表
您還可以使用接受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)
這裡建立了一個新陣列,然後用它來初始化一個列表。這將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)
在此例子中,我們從包含兩個元素的列表開始,並使用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表格並轉換為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>類的實例來初始化清單,其中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的功能。




