C# 列印清單:快速教學課程
在 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 };
}
}使用循環列印列表
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);
}
}
}這種方法簡潔易懂,適用於大多數情況。
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]}");
}
}
}當您需要存取索引或希望在列印過程中應用特定邏輯時,這種方法是有益的。
反向列印清單元素
可以使用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);
}
}
}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);
}
}
}元素數量計數和列印
計算清單中元素的數量是一個常見的操作。 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}");
}
}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}");
}
}列印指定索引處的清單元素
列印指定索引處的元素需要存取該索引處的清單。 這樣一來,您就可以存取不同位置的元素,並確保您能夠處理潛在的索引超出範圍的情況:
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.");
}
}
}這些範例為在各種場景下列印清單元素奠定了基礎。 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);
}
}在這裡,列表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));
}
}在這個例子中,LINQ 用於從原始清單中篩選出偶數。 Where Where()方法配合 lambda 表達式使用,而ToList()方法用於將結果轉換回列表。
自訂物件和 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);
}
}
}透過重寫Person類別中的ToString()方法,您可以控制該類別的實例如何表示為字串。 這樣可以提高列印出來的清單的可讀性。
隆重介紹 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");
}
}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");
}
}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);
}
}若要更了解所使用的類別和方法,請造訪API 參考頁面。
結論
在 C# 中列印清單需要根據資料的複雜性和所需的輸出選擇正確的方法。 無論是使用簡單的迴圈、 String.Join() 、LINQ,或是為自訂物件自訂ToString()方法,了解這些方法都能幫助您有效地在 C# 應用程式中顯示清單的內容。 嘗試這些方法,選擇最適合您特定使用情況的方法。
如果您想要精準、易用且快速的列印庫, IronPrint是您的理想之選。 無論您是在建立 Web 應用程式、使用 MAUI、Avalonia 或任何與 .NET 相關的項目,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#中篩選並列印清單中的特定元素?
LINQ 方法(例如Where方法)可用於從清單中篩選和選擇特定元素。篩選後的結果可以使用 IronPrint 列印出來。
如何在 .NET 中安裝列印庫?
您可以使用 NuGet 套件管理器控制台的Install-Package IronPrint指令安裝 IronPrint,也可以透過 Visual Studio 的 NuGet 套件管理器安裝 IronPrint。
IronPrint 為 .NET 開發人員提供哪些功能?
IronPrint 提供跨平台相容性、對各種文件格式的支援、靜默列印、列印對話方塊和可自訂的列印設置,使其成為 .NET 開發人員的強大選擇。






