IRONSOFTWAREHOME
.NET幫助

C# 列印列表:快速教程

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

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

使用迴圈列印列表

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

這種方法簡潔易讀,非常適合大多數情境。

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

當您需要存取索引或希望在列印過程中應用特定邏輯時,這種方法非常有用。

反向列印列表元素

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

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

計算元素數量並列印

計算列表中元素的數量是常見的操作。 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}");
    }
}

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;

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

這些例子為不同情境中的列表元素列印提供了基礎。 還有其他有用的方法,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);
    }
}

在這裡,列表元素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));
    }
}

在此範例中,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);
        }
    }
}

通過在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程式庫:

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

2. 使用對話框列印

它還提供了一種顯示print對話框的方法,以便更好地控制列印過程。 ShowPrintDialogAsync方法也可以用於異步列印。

using IronPrint;

class Program
{
    static void Main()
    {
        // Show print dialog
        Printer.ShowPrintDialog("newDoc.pdf");
    }
}

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

要更好地理解使用的類和方法,請存取API 參考頁面。

結論

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

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

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

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

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費
現場演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲得非義務性諮詢
完成下列表單或發郵件到sales@ironsoftware.com
您的資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立