跳至頁尾內容
.NET幫助

C# 列印列表:快速教程

在C#中,列印列表是一項常見的任務,有多種方式可以實現,提供靈活性和客製化。 列表是C#中基本的資料結構,能夠列印其內容對於除錯、記錄或向使用者顯示資訊至關重要。

在本文中,我們將探索不同的方法來列印C#中的列表

C# 列表的基本知識

在C#中,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 };
    }
}
Imports System
Imports System.Collections.Generic

Class Program
    Shared Sub Main()
        Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
    End Sub
End Class
$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 Count方法

如果偏好使用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() 方法和 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

通過在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# 中列印列表涉及選擇基於資料複雜度和所需輸出的方法。 無論是使用簡單的迴圈,ToString()方法,了解這些方法能夠有效地展示您的 C# 應用中的列表內容。 試驗這些技術,選擇最適合您具體使用情境的技術。

IronPrint是您的首選列印庫,如果您想要準確性、易用性和速度。 無論您是在構建WebApps,使用MAUI,Avalonia,或任何與.NET相關的內容,IronPrint都能支持您。 有關IronPrint的更詳細資訊,請存取此文件頁面

IronPrint是一個付費程式庫,但您可以獲得免費試用。 從此處下載程式庫並試試看!

常見問題

如何在C#中列印清單?

您可以使用IronPrint透過foreachfor迴圈遍歷清單元素,並將格式化的輸出傳遞給IronPrint進行列印。

使用動態陣列在C#有哪些好處?

在C#中,動態陣列或清單提供了靈活性,因為它們可以增長或縮減大小。它們是System.Collections.Generic命名空間的一部分,允許有效地處理和操作集合。

如何在C#中反轉並列印清單?

要以反向順序列印清單,您可以使用Reverse方法或LINQ的OrderByDescending,然後使用IronPrint列印反轉的清單。

如何將清單格式化為字串以供列印?

您可以使用String.Join方法將清單元素連接成具有指定分隔符的單一格式化字串。然後使用IronPrint列印此格式化字串。

ToString方法在列印自定義物件時的角色是什麼?

透過覆寫ToString方法,您可以定義自訂物件實例如何表示為字串,這在使用IronPrint列印時能提高可讀性。

如何在C#中篩選並列印清單中的特定元素?

LINQ方法如Where可用來篩選並選擇清單中的特定元素。篩選過的結果可以使用IronPrint進行列印。

如何安裝.NET的列印程式庫?

您可以使用NuGet封裝管理控制台執行命令Install-Package IronPrint來安裝IronPrint,或者通過Visual Studio的NuGet封裝管理器進行安裝。

IronPrint為.NET開發者提供了哪些功能?

IronPrint提供跨平台相容性,支持各種文件格式、靜默列印、列印對話框及可自定義的列印設置,使其成為.NET開發者的強大選擇。

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

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話