.NET 帮助

C# 打印列表(开发人员的工作原理)

发布 2024年五月20日
分享:

在 C# 中,打印列表是一项常见的任务,可以通过多种方式完成,提供了灵活性和定制性。列表是 C# 的基本数据结构,能够打印其内容对于调试、记录或向用户显示信息至关重要。

在本文中,我们将探讨不同的方法来 用 C# 打印列表.

C&num 中列表的基本原理;

在 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 };
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

使用循环打印列表

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
VB   C#

这种方法简洁易读,适合大多数情况。

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
VB   C#

当您需要访问索引或希望在打印过程中应用特定逻辑时,这种方法非常有用。

反向打印列表元素

使用 Reverse 方法可以反序打印列表。该方法将列表中元素的顺序颠倒过来,这样就可以遍历并打印这些元素。

1.使用 List.Reverse 方法

例如,您可以使用 Reverse 方法按相反顺序打印列表,然后打印每个元素。

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Reverse();
foreach (var number in numbers)
{
    Console.WriteLine(number);
}
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Reverse();
foreach (var number in numbers)
{
    Console.WriteLine(number);
}
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
VB   C#

2.使用 LINQ OrderByDescending

您还可以使用 按降序排列 方法,用一个键从 LINQ 通用类中排列指定的元素集合:

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);
}
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);
}
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
VB   C#

计算元素数量并打印

计算列表中元素的个数是一种常见的操作。为此,可以使用 Count 属性或 Count 方法。一旦获得计数,就可以轻松打印出来。

1.使用 List.Count 属性

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count;
Console.WriteLine($"Number of elements: {count}");
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count;
Console.WriteLine($"Number of elements: {count}");
Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"}
Dim count As Integer = names.Count
Console.WriteLine($"Number of elements: {count}")
VB   C#

2.使用 LINQ 计数方法

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count();
Console.WriteLine($"Number of elements: {count}");
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int count = names.Count();
Console.WriteLine($"Number of elements: {count}");
Dim names As New List(Of String) From {"Alice", "Bob", "Charlie"}
Dim count As Integer = names.Count()
Console.WriteLine($"Number of elements: {count}")
VB   C#

在指定索引处打印列表元素

在指定索引处打印元素涉及访问该索引处的列表。这使您可以访问不同位置的元素,并确保您能处理潜在的索引超出范围的情况:

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

这些示例为在各种情况下打印列表元素奠定了基础。此外 列表 类提供的功能,可在印刷中使用。

一些有用的方法如下

  • 删除:"删除() 方法移除 C# 列表中的第一个出现点
  • RemoveAll:` RemoveAll() 方法用于根据指定的谓词删除元素。
  • RemoveRange:` 移除范围() 方法根据指定的索引和计数参数删除一系列元素。
  • 添加() 方法只能在列表末尾添加一个元素。
  • 添加范围:` AddRange() 方法可用于将指定集合的元素添加到末尾。
  • 清除() 方法会删除列表中的所有元素。
  • 插入:` 插入() 方法在指定索引处向列表中插入一个元素。
  • ForEach:` ForEach() 方法用于对每个元素执行特定操作,例如有效打印每个列表值。

  • ToArray 方法() 方法将列表复制到一个新的 var 数组中。

现在,您可以选择最适合您要求的方法,并提高 C# 代码的可读性和效率。

String.Join 方法

字符串 字符串.Join 方法提供了一种简洁的方法,可将列表中的元素用指定的分隔符连接成单个字符串。这对于创建列表的格式化字符串表示非常有用。

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers);
Console.WriteLine(result);
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers);
Console.WriteLine(result);
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Dim result As String = String.Join(", ", numbers)
Console.WriteLine(result)
VB   C#

在这里,列表 numbers 中的元素被连接成一个字符串,并用逗号和空格隔开,从而得到格式化的输出结果。在打印列表元素之前,还可以使用排序方法。

使用 LINQ 解决高级问题

对于要在打印前过滤、转换或格式化元素的更复杂情况,语言集成查询 (LINQ) 是有益的。

using System.Linq;
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.Linq;
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.Linq
Private numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
Private evenNumbers As List(Of Integer) = numbers.Where(Function(n) n Mod 2 = 0).ToList()
Console.WriteLine("Even numbers: " & String.Join(", ", evenNumbers))
VB   C#

在本例中,LINQ 用于从原始列表中过滤出偶数。其中()方法使用 lambda 表达式,而 `ToList()方法用于将结果转换回列表。

C# 打印列表(开发人员如何操作):图 1 - 控制台输出:偶数:2, 4

自定义对象和 ToString() 方法

如果您有一个自定义对象列表,建议覆盖对象类中的 ToString 方法,以获得有意义的表示。下面的示例演示了如何做到这一点:

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);
    }
    }
}
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);
    }
    }
}
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
VB   C#

通过覆盖 `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+
  • 操作系统视窗 (7+, Server 2016+)MacOS (10+)iOS (11+), Android API 21+ (v5 "棒棒糖")

  • 项目类型:移动 (Xamarin & MAUI & Avalonia)桌面 (WPF & MAUI & Windows Avalonia)控制台 (应用程序和图书馆)

2.支持的格式

  • 处理各种文档格式,包括 PDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE 和 BITMAP。
  • 根据文档要求自定义打印设置

3.安装简便

安装 IronPrint 库:

Install-Package IronPrint
Install-Package IronPrint
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPrint
VB   C#

或者,也可以使用 Visual Studio 将其安装到项目中。在 "解决方案资源管理器 "中右键单击项目,然后单击 "管理解决方案的 NuGet 包管理器"。在 NuGet 浏览选项卡中搜索"ironprint",从搜索结果中选择最新版本的 IronPrint 软件包,然后点击安装按钮将其添加到项目中。

使用 IronPrint 打印:代码示例

1.打印文档

IronPrint 可使用简单的 打印 "方法.如果物理打印机不可用,则使用操作系统指定的默认打印机打印。

using IronPrint;
// Print the document
Printer.Print("newDoc.pdf");
using IronPrint;
// Print the document
Printer.Print("newDoc.pdf");
Imports IronPrint
' Print the document
Printer.Print("newDoc.pdf")
VB   C#

2.使用对话框打印

它还提供了一种专用方法来显示 打印 "对话框 以更好地控制打印。ShowPrintDialogAsync "方法也可用于异步打印。

using IronPrint;
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
using IronPrint;
// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
Imports IronPrint
' Show print dialog
Printer.ShowPrintDialog("newDoc.pdf")
VB   C#

3.自定义打印设置

IronPrint 提供多种 打印 "设置s 可对打印文件进行细粒度控制。

using IronPrint;
// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
// Print the document
Printer.Print("newDoc.pdf", printSettings);
using IronPrint;
// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;
// Print the document
Printer.Print("newDoc.pdf", printSettings);
Imports IronPrint
' Configure print settings
Private printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait
' Print the document
Printer.Print("newDoc.pdf", printSettings)
VB   C#

要更好地了解所使用的类和方法,请访问 API 参考资料 page.

结论

在 C# 中打印列表需要根据数据的复杂性和所需的输出来选择正确的方法。无论是使用简单的循环、String.Join()、LINQ 或自定义ToString()了解了这些方法,您就能在 C# 应用程序中有效地显示列表内容。请尝试使用这些技术,并选择最适合您特定用例的技术。

IronPrint 如果您需要精确、易用和快速的打印库,IronPrint 是您的首选。无论您是要构建 WebApps,还是要使用 MAUI、Avalonia 或任何与 .NET 相关的应用程序,IronPrint 都能为您提供支持。有关 IronPrint 的更多详细信息,请访问此处 文献资料 page.

IronPrint 是一个付费图书馆,但它是一个 免费试用.从以下网址下载资料库 这里 试一试!

< 前一页
C# 打印功能(开发人员如何使用)
下一步 >
C# 打印到控制台(开发人员操作指南)

准备开始了吗? 版本: 2024.8 刚刚发布

免费NuGet下载 总下载量: 7,289 查看许可证 >