IRONSOFTWAREHOME
.NET 帮助

C# 打印列表:快速教程

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

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

使用循环打印列表

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 计数方法

如果更倾向于使用 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);
        }
    }
}

通过在 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. 安装简便

using 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# 中打印列表需要根据数据的复杂性和所需的输出选择正确的方法。 无论是使用简单的循环,String.Join(),LINQ,还是为自定义对象定制 ToString() 方法,理解这些方法可以使您在C#应用程序中有效地显示列表的内容。 尝试这些方法,选择最适合您具体使用情况的方法。

如果您想要精准、易用和快速的打印库, IronPrint是您的理想之选。 无论您是在构建 Web 应用程序、使用 MAUI、Avalonia 还是任何与 .NET 相关的项目,IronPrint 都能为您提供支持。 有关 IronPrint 的更多详细信息,请访问此文档页面

IronPrint 是一个付费库,但提供免费试用。 从这里下载库文件并试用一下!

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

相关文章

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 天试用密钥
无需信用卡或创建账户