.NET幫助 C# 打印列表:快速教程 Jacob Mellor 更新:7月 28, 2025 下載 IronPrint NuGet 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 在 C# 中,列印清單是一項常見的任務,可以透過多種方式實現,從而提供靈活性和自訂性。 清單是 C# 中的基本資料結構,能夠列印其內容對於偵錯、日誌記錄或向使用者顯示資訊至關重要。 在本文中,我們將探討在 C# 中列印清單的不同方法。 C# 中列表的基礎知識 在 C# 中, list是一種動態數組,其大小可以增長或縮小。它屬於System.Collections.Generic命名空間,為處理項目集合提供了靈活性和高效性。 以下程式碼建立一個簡單的數字列表: using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; } } using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; } } IRON VB CONVERTER ERROR developers@ironsoftware.com $vbLabelText $csharpLabel 使用循環列印列表 1. 使用foreach循環 列印列表元素的傳統且直接的方法是使用foreach循環。以下是一個簡單的範例: using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Printing list using foreach loop:"); foreach (var number in numbers) { Console.WriteLine(number); } } } using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; Console.WriteLine("Printing list using foreach loop:"); foreach (var number in numbers) { Console.WriteLine(number); } } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5} Console.WriteLine("Printing list using foreach loop:") For Each number In numbers Console.WriteLine(number) Next number End Sub End Class $vbLabelText $csharpLabel 這種方法簡潔易懂,適用於大多數情況。 2. 使用for循環 如果您需要更精確地控制索引或希望有條件地列印元素,可以使用for迴圈。以下是一個字串列表的範例: using System; using System.Collections.Generic; class Program { public static void Main() { // Create list of strongly typed objects List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" }; Console.WriteLine("Printing list using for loop:"); for (int index = 0; index < colors.Count; index++) { Console.WriteLine($"Color at index {index}: {colors[index]}"); } } } using System; using System.Collections.Generic; class Program { public static void Main() { // Create list of strongly typed objects List<string> colors = new List<string> { "Red", "Green", "Blue", "Yellow" }; Console.WriteLine("Printing list using for loop:"); for (int index = 0; index < colors.Count; index++) { Console.WriteLine($"Color at index {index}: {colors[index]}"); } } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() ' Create list of strongly typed objects Dim colors As New List(Of String) From {"Red", "Green", "Blue", "Yellow"} Console.WriteLine("Printing list using for loop:") For index As Integer = 0 To colors.Count - 1 Console.WriteLine($"Color at index {index}: {colors(index)}") Next index End Sub End Class $vbLabelText $csharpLabel 當您需要存取索引或希望在列印過程中應用特定邏輯時,這種方法是有益的。 反向列印清單元素 可以使用Reverse方法以相反的順序列印清單。 此方法會反轉清單中元素的順序,從而允許您遍歷並列印它們。 1. 使用 List.Reverse 方法 例如,您可以使用Reverse方法以相反的順序列印列表,然後列印每個元素。 using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; numbers.Reverse(); foreach (var number in numbers) { Console.WriteLine(number); } } } using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; numbers.Reverse(); foreach (var number in numbers) { Console.WriteLine(number); } } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5} numbers.Reverse() For Each number In numbers Console.WriteLine(number) Next number End Sub End Class $vbLabelText $csharpLabel 2. 使用 LINQ OrderByDescending 您也可以使用帶有鍵的OrderByDescending方法對 LINQ 通用類別中的指定元素集合進行排序: using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var reversedNumbers = numbers.OrderByDescending(n => n); foreach (var number in reversedNumbers) { Console.WriteLine(number); } } } using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var reversedNumbers = numbers.OrderByDescending(n => n); foreach (var number in reversedNumbers) { Console.WriteLine(number); } } } Imports System Imports System.Collections.Generic Imports System.Linq Friend Class Program Public Shared Sub Main() Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5} Dim reversedNumbers = numbers.OrderByDescending(Function(n) n) For Each number In reversedNumbers Console.WriteLine(number) Next number End Sub End Class $vbLabelText $csharpLabel 元素數量計數和列印 計算清單中元素的數量是一個常見的操作。 Count屬性可用於此目的。 統計完成後,就可以輕鬆列印出來。 1. 使用 List.Count 屬性 using System; using System.Collections.Generic; class Program { public static void Main() { List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; int count = names.Count; Console.WriteLine($"Number of elements: {count}"); } } using System; using System.Collections.Generic; class Program { public static void Main() { List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; int count = names.Count; Console.WriteLine($"Number of elements: {count}"); } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"} Dim count As Integer = names.Count Console.WriteLine($"Number of elements: {count}") End Sub End Class $vbLabelText $csharpLabel 2. 使用 LINQ 計數法 如果更傾向於使用 LINQ,它也可以用於計數: using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; int count = names.Count(); Console.WriteLine($"Number of elements: {count}"); } } using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; int count = names.Count(); Console.WriteLine($"Number of elements: {count}"); } } Imports System Imports System.Collections.Generic Imports System.Linq Friend Class Program Public Shared Sub Main() Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"} Dim count As Integer = names.Count() Console.WriteLine($"Number of elements: {count}") End Sub End Class $vbLabelText $csharpLabel 列印指定索引處的清單元素 列印指定索引處的元素需要存取該索引處的清單。 這樣一來,您就可以存取不同位置的元素,並確保您能夠處理潛在的索引超出範圍的情況: using System; using System.Collections.Generic; class Program { public static void Main() { List<double> prices = new List<double> { 19.99, 29.99, 39.99 }; int indexToPrint = 1; if (indexToPrint >= 0 && indexToPrint < prices.Count) { Console.WriteLine($"Element at index {indexToPrint}: {prices[indexToPrint]}"); } else { Console.WriteLine("Index out of range."); } } } using System; using System.Collections.Generic; class Program { public static void Main() { List<double> prices = new List<double> { 19.99, 29.99, 39.99 }; int indexToPrint = 1; if (indexToPrint >= 0 && indexToPrint < prices.Count) { Console.WriteLine($"Element at index {indexToPrint}: {prices[indexToPrint]}"); } else { Console.WriteLine("Index out of range."); } } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() Dim prices As New List(Of Double) From {19.99, 29.99, 39.99} Dim indexToPrint As Integer = 1 If indexToPrint >= 0 AndAlso indexToPrint < prices.Count Then Console.WriteLine($"Element at index {indexToPrint}: {prices(indexToPrint)}") Else Console.WriteLine("Index out of range.") End If End Sub End Class $vbLabelText $csharpLabel 這些範例為在各種場景下列印清單元素奠定了基礎。 list類別還提供了其他一些可用於列印的有用方法。 一些有用的方法包括: Remove: Remove()方法會刪除 C# 清單中的第一個符合項目。 RemoveAll: RemoveAll()方法用於根據指定的謂詞刪除元素。 RemoveRange: RemoveRange()方法根據指定的索引和計數參數刪除一系列元素。 Add: Add()方法只能在清單末尾新增一個元素。 AddRange: AddRange()方法可以將指定集合中的元素加入到結尾。 Clear: Clear()方法會從清單中刪除所有元素。 Insert: Insert()方法將元素插入到清單中指定的索引位置。 ForEach: ForEach()方法用於對每個元素執行特定操作,例如,有效地列印每個清單值。 ToArray: ToArray()方法將清單複製到一個新陣列中。 現在您可以選擇最符合您需求的方法,提高 C# 程式碼的可讀性和效率。 String.Join 方法 String.Join方法提供了一種簡潔的方法,可以將清單中的元素以指定的分隔符號連接成一個字串。 這對於建立清單的格式化字串表示形式非常有用。 using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; string result = string.Join(", ", numbers); Console.WriteLine(result); } } using System; using System.Collections.Generic; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; string result = string.Join(", ", numbers); Console.WriteLine(result); } } Imports System Imports System.Collections.Generic Friend Class Program Public Shared Sub Main() Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5} Dim result As String = String.Join(", ", numbers) Console.WriteLine(result) End Sub End Class $vbLabelText $csharpLabel 在這裡,列表numbers的各個元素被連接成一個字串,字串之間用逗號和空格分隔,從而得到格式化的輸出。 在列印清單元素之前也可以使用排序方法。 LINQ在進階場景中的應用 對於更複雜的場景,例如在列印之前需要篩選、轉換或格式化元素,語言整合查詢 ( LINQ ) 會很有幫助。 using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers)); } } using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; List<int> evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers)); } } Imports System Imports System.Collections.Generic Imports System.Linq Friend Class Program Public Shared Sub Main() Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5} Dim evenNumbers As List(Of Integer) = numbers.Where(Function(n) n Mod 2 = 0).ToList() Console.WriteLine("Even numbers: " & String.Join(", ", evenNumbers)) End Sub End Class $vbLabelText $csharpLabel 在這個例子中,LINQ 用於從原始清單中篩選出偶數。 Where Where()方法配合 lambda 表達式使用,而ToList()方法用於將結果轉換回列表。 C# 列印清單(開發者操作指南):圖 1 - 控制台輸出:偶數:2、4 自訂物件和 ToString() 方法 如果您有一系列自訂對象,建議您在物件類別中重寫ToString方法,以便進行有意義的表示。 以下範例示範如何操作: using System; using System.Collections.Generic; class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return $"{Name}, {Age} years old"; } } class Program { public static void Main() { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 } }; foreach (Person person in people) { Console.WriteLine(person); } } } using System; using System.Collections.Generic; class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return $"{Name}, {Age} years old"; } } class Program { public static void Main() { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 25 } }; foreach (Person person in people) { Console.WriteLine(person); } } } Imports System Imports System.Collections.Generic Friend Class Person Public Property Name() As String Public Property Age() As Integer Public Overrides Function ToString() As String Return $"{Name}, {Age} years old" End Function End Class Friend Class Program Public Shared Sub Main() Dim people As New List(Of Person) From { New Person With { .Name = "Alice", .Age = 30 }, New Person With { .Name = "Bob", .Age = 25 } } For Each person As Person In people Console.WriteLine(person) Next person End Sub End Class $vbLabelText $csharpLabel 透過重寫Person類別中的ToString()方法,您可以控制該類別的實例如何表示為字串。 這樣可以提高列印出來的清單的可讀性。 C# 列印清單(開發者使用方法):圖 2 - 控制台輸出 隆重介紹 IronPrint - C# 列印庫 IronPrint是一款功能強大且易於部署的列印庫,它優先考慮準確性、易用性和速度。 它具有跨平台支援和與各種文件格式的兼容性,對於尋求在應用程式中實現高效列印解決方案的 .NET 開發人員來說,它是一款非常有價值的工具。 C# 列印清單(開發者使用方法):圖 3 - IronPrint for .NET:C# 列印庫 主要功能 以下是 IronPrint 在 C# 應用程式中列印紙本文件方面脫穎而出的一些重要關鍵特性: 1. 跨平台相容性 .NET 版本支援:.NET 8、7、6、5 和 Core 3.1+ 作業系統:Windows(7+,Server 2016+),macOS(10+),iOS(11+),Android API 21+(v5"Lollipop") 專案類型:行動裝置(Xamarin、MAUI 和 Avalonia)、桌面(WPF、MAUI 和 Windows Avalonia)、控制台(應用程式和函式庫) 2. 支援的格式 處理各種文件格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP。 依文件要求自訂列印設定。 3. 安裝簡便 使用 NuGet 套件管理器控制台安裝IronPrint庫: Install-Package IronPrint 或者,您可以使用 Visual Studio 將其安裝到您的專案中。 在解決方案資源管理器中以滑鼠右鍵按一下項目,然後按一下"管理解決方案的 NuGet 套件管理員"。 在 NuGet 瀏覽標籤中,搜尋"ironprint",從搜尋結果中選擇最新版本的 IronPrint 包,然後按一下"安裝"按鈕將其新增至您的專案。 使用 IronPrint 進行列印:程式碼範例 1. 列印文檔 IronPrint 提供使用簡單Print方式的靜默列印文件功能。 如果實體印表機不可用,則使用作業系統指定的預設印表機進行列印。 using IronPrint; class Program { static void Main() { // Print the document Printer.Print("newDoc.pdf"); } } using IronPrint; class Program { static void Main() { // Print the document Printer.Print("newDoc.pdf"); } } Imports IronPrint Friend Class Program Shared Sub Main() ' Print the document Printer.Print("newDoc.pdf") End Sub End Class $vbLabelText $csharpLabel 2. 帶對話框的列印 它還提供了一種專門的方法來顯示print對話框,以便在列印時更好地進行控制。 ShowPrintDialogAsync方法也可以用於非同步列印。 using IronPrint; class Program { static void Main() { // Show print dialog Printer.ShowPrintDialog("newDoc.pdf"); } } using IronPrint; class Program { static void Main() { // Show print dialog Printer.ShowPrintDialog("newDoc.pdf"); } } Imports IronPrint Friend Class Program Shared Sub Main() ' Show print dialog Printer.ShowPrintDialog("newDoc.pdf") End Sub End Class $vbLabelText $csharpLabel 3. 自訂列印設定 IronPrint 提供各種print設置,可對文件列印進行精細控制。 using IronPrint; class Program { static void Main() { // Configure print settings PrintSettings printSettings = new PrintSettings() { Dpi = 150, NumberOfCopies = 2, PaperOrientation = PaperOrientation.Portrait }; // Print the document Printer.Print("newDoc.pdf", printSettings); } } using IronPrint; class Program { static void Main() { // Configure print settings PrintSettings printSettings = new PrintSettings() { Dpi = 150, NumberOfCopies = 2, PaperOrientation = PaperOrientation.Portrait }; // Print the document Printer.Print("newDoc.pdf", printSettings); } } Imports IronPrint Friend Class Program Shared Sub Main() ' Configure print settings Dim printSettings As New PrintSettings() With { .Dpi = 150, .NumberOfCopies = 2, .PaperOrientation = PaperOrientation.Portrait } ' Print the document Printer.Print("newDoc.pdf", printSettings) End Sub End Class $vbLabelText $csharpLabel 若要更了解所使用的類別和方法,請造訪API 參考頁面。 結論 在 C# 中列印清單需要根據資料的複雜性和所需的輸出選擇正確的方法。 無論是使用簡單的迴圈、 String.Join() 、LINQ,或是為自訂物件自訂ToString()方法,了解這些方法都能幫助您有效地在 C# 應用程式中顯示清單的內容。 嘗試這些方法,選擇最適合您特定使用情況的方法。 如果您想要精準、易用且快速的列印庫, IronPrint是您的理想之選。 無論您是在建立 Web 應用程式、使用 MAUI、Avalonia 或任何與 .NET 相關的項目,IronPrint 都能為您提供支援。 有關 IronPrint 的更多詳細信息,請訪問此文件頁面。 IronPrint 是一個付費圖書館,但提供免費試用。 從這裡下載庫文件並試用一下! 常見問題解答 如何在 C# 中列印清單? 您可以使用 IronPrint 在 C# 中打印列表,方法是使用 foreach 或 for 環路遍歷列表元素,然後將格式化的輸出傳給 IronPrint 進行打印。 在 C# 中使用動態陣列有什麼好處? C# 中的動態陣列或清單提供了彈性,因為它們的大小可以增大或縮小。它們是 System.Collections.Generic 命名空間的一部分,允許有效地處理和操作集合。 如何在 C# 中反向列印清單? 若要以相反順序列印清單,您可以使用 Reverse 方法或 LINQ 的 OrderByDescending 方法,然後再使用 IronPrint 列印反向清單。 如何將清單格式化為字串以便列印? 您可以使用 String.Join 方法將清單元素串連成一個具有指定分隔符的單一格式化字串。然後可以使用 IronPrint 來列印這個格式化的字串。 ToString 方法在列印自訂物件中扮演什麼角色? 透過覆寫 ToString 方法,您可以定義自訂物件的實體如何表示為字串,這可提高使用 IronPrint 列印時的可讀性。 如何在 C# 中從清單中篩選並列印特定元素? 像 Where 之類的 LINQ 方法可用於篩選和選擇列表中的特定元素。篩選後的結果可以使用 IronPrint 進行列印。 如何為 .NET 安裝列印函式庫? 您可以使用 NuGet Package Manager Console,使用 Install-Package IronPrint 命令或透過 Visual Studio 的 NuGet Package Manager 安裝 IronPrint。 IronPrint 為 .NET 開發人員提供哪些功能? IronPrint 提供跨平台兼容性、對各種文件格式的支援、無聲列印、列印對話方塊以及可自訂的列印設定,使其成為 .NET 開發人員的強大選擇。 Jacob Mellor 立即與工程團隊聊天 首席技术官 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 技術的創新,同時指導新一代技術領袖。 相關文章 更新7月 28, 2025 如何有效地使用 C# 打印行 在本文中,我們將探索與 C# 打印行有關的各種方法和技術。 閱讀更多 更新6月 22, 2025 C# 打印變量:簡化您的代碼 在這篇綜合文章中,我們將探索在 C# 中打印變量的各種方面,涵蓋不同的數據類型,格式化選項以及高級技術。 閱讀更多 更新7月 28, 2025 精通 C# 打印函數:開發者指南 C# 打印的核心在於 Console.WriteLine 方法。這是顯示控制台上格式化輸出信息的首選函數 閱讀更多 精通 C# 打印函數:開發者指南C# 打印控制台:逐步指南