Lista wydruku w języku C#: krótki samouczek
W C# drukowanie listy to często wykonywane zadanie, które można zrealizować na różne sposoby, oferując elastyczność i personalizację. Listy są podstawowymi strukturami danych w C#, a możliwość wydrukowania ich zawartości jest kluczowa dla debugowania, logowania lub wyświetlania informacji użytkownikom.
W tym artykule zbadamy różne metody jak drukować listę w C#.
Podstawy Listy w C
W C#, list jest dynamiczną tablicą, która może rosnąć lub maleć. Jest częścią przestrzeni nazw System.Collections.Generic i zapewnia elastyczność oraz wydajność w obsłudze kolekcji elementów. Poniższy kod tworzy prostą listę liczb:
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
Drukowanie listy przy użyciu pętli
1. Użycie foreach Loop
Tradycyjny i prosty sposób drukowania elementów listy to użycie pętli foreach. Oto prosty przykład:
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
Ta metoda jest zwięzła i czytelna, co czyni ją odpowiednią dla większości scenariuszy.
2. Użycie for Loop
Jeśli potrzebujesz większej kontroli nad indeksem lub chcesz wydrukować elementy warunkowo, możesz użyć pętli for. Oto przykład listy stringów:
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
To podejście jest korzystne, gdy wymagana jest dostęp do indeksu lub zastosowanie określonej logiki podczas drukowania.
Drukowanie elementów listy w odwrotnej kolejności
Drukowanie listy w odwrotnej kolejności można osiągnąć, wykorzystując metodę Reverse. Ta metoda odwraca porządek elementów na liście, co pozwala na ich iterację i drukowanie.
1. Używanie metody List.Reverse
Na przykład, można wydrukować listę w odwrotnej kolejności, używając metody Reverse, a następnie drukując każdy element.
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
2. Using LINQ OrderByDescending
Można również użyć metody OrderByDescending z kluczem, aby ułożyć określoną kolekcję elementów z klasy ogólnej 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
Liczba elementów i drukowanie
Liczenie liczby elementów na liście to wspólna operacja. W tym celu można użyć właściwości Count. Po uzyskaniu liczby, można go łatwo wydrukować.
1. Używanie właściwości 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
2. Używanie metody LINQ Count
Jeśli preferowane jest LINQ, można je również wykorzystać do liczenia:
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
Drukowanie elementów listy na określonym indeksie
Drukowanie elementów na określonym indeksie polega na uzyskaniu dostępu do listy na tym indeksie. To pozwala uzyskać dostęp do elementów w różnych lokalizacjach i zapewnia obsługę potencjalnych scenariuszy nieprawidłowego zakresu indeksów:
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
Te przykłady stanowią podstawę do drukowania elementów listy w różnych scenariuszach. Istnieją inne przydatne metody, które klasa list oferuje do drukowania.
Niektóre przydatne metody to:
Remove:MetodaRemove()usuwa pierwsze wystąpienie na liście C#.RemoveAll:MetodaRemoveAll()służy do usuwania elementów na podstawie określonego predykatu.RemoveRange:MetodaRemoveRange()usuwa zakres elementów na podstawie określonych parametrów indeksu i liczby.Add:MetodaAdd()może dodać tylko jeden element na końcu listy.AddRange:MetodaAddRange()może dodać elementy określonej kolekcji na końcu.Clear:MetodaClear()usuwa wszystkie elementy z listy.Insert:MetodaInsert()wstawia element na liście pod wskazanym indeksem.ForEach:MetodaForEach()jest używana do wykonywania określonych działań na każdym elemencie, np. efektywnego drukowania każdej wartości listy.ToArray:MetodaToArray()kopiuje listę do nowej tablicy.
Teraz możesz wybrać podejście, które najlepiej odpowiada Twoim wymaganiom i zwiększa czytelność i efektywność Twojego kodu C#.
Metoda String.Join
Metoda String.Join zapewnia zwięzły sposób łączenia elementów listy w jeden string z określonym separatorem. Może to być przydatne do tworzenia sformatowanej reprezentacji łańcucha listy.
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
Tutaj elementy listy numbers są łączone w string, oddzielony przecinkiem i spacją, co daje sformatowany wynik. Metoda sortujaca może być używana przed drukowaniem elementów listy.
Użycie LINQ dla zaawansowanych scenariuszy
W przypadku bardziej złożonych scenariuszy, gdzie chcesz filtrować, transformować lub formatować elementy przed drukowaniem, Language-Integrated Query (LINQ) może być korzystny.
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
W tym przykładzie, LINQ jest użyty do przefiltrowania parzystych liczb z oryginalnej listy. Metoda Where() jest zastosowana z wyrażeniem lambda, a metoda ToList() jest użyta do przekonwertowania wyniku z powrotem na listę.

Obiekty niestandardowe i metoda ToString()
Jeśli posiadasz listę niestandardowych obiektów, zaleca się nadpisanie metody ToString w klasie obiektu dla sensownej reprezentacji. Poniższy przykład pokazuje, jak to zrobić:
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
Poprzez nadpisanie metody ToString() w klasie Person, kontrolujesz, jak instancje klasy są reprezentowane jako stringi. To poprawia czytelność Twojej listy, gdy jest drukowana.

Przedstawienie IronPrint - Biblioteka drukowania C
IronPrint wyróżnia się jako potężna i wdrażalna biblioteka drukowania, kładąc nacisk na dokładność, łatwość użycia i szybkość. Jej wsparcie międzyplatformowe i zgodność z różnorodnymi formatami dokumentów czynią ją cennym narzędziem dla programistów .NET szukających wydajnych rozwiązań drukowania w swoich aplikacjach.

Najważniejsze cechy
Oto niektóre kluczowe funkcje, które sprawiają, że IronPrint wyróżnia się w drukowaniu fizycznych dokumentów w aplikacjach C#:
1. Zgodność międzyplatformowa
- Obsługa wersji .NET: .NET 8, 7, 6, 5 i Core 3.1+
- Operating Systems: Windows (7+, Server 2016+), macOS (10+), iOS (11+), Android API 21+ (v5 "Lollipop")
- Typy projektów: mobilne (Xamarin & MAUI & Avalonia), desktopowe (WPF & MAUI & Windows Avalonia), konsolowe (aplikacje i biblioteki)
2. Obsługiwane formaty
- Obsługuje różne formaty dokumentów, w tym PDF, PNG, HTML, TIFF, GIF, JPEG, IMAGE i BITMAP.
- Dostosuj ustawienia drukowania według wymagań dokumentu.
3. Łatwa instalacja
Zainstaluj bibliotekę IronPrint za pomocą konsoli Menedżera pakietów NuGet:
Install-Package IronPrint
Alternatywnie można zainstalować go w projekcie za pomocą programu Visual Studio. Kliknij prawym przyciskiem myszy na projekt w Eksploratorze rozwiązań i kliknij Zarządzaj Menedżerem Pakietu NuGet dla Rozwiązań. W zakładce przeglądania NuGet poszukaj IronPrint, wybierz najnowszą wersję pakietu IronPrint z wyników wyszukiwania, a następnie kliknij przycisk Zainstaluj, aby dodać go do projektu.
Drukowanie z IronPrint: Przykłady kodu
1. Drukuj dokument
IronPrint oferuje ciche drukowanie dokumentów, używając prostej metody Print. Jeśli fizyczna drukarka nie jest dostępna, drukuje za pomocą domyślnej drukarki określonej przez system operacyjny.
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
2. Drukuj z dialogiem
Dzięki temu dostępna jest również dedykowana metoda do wyświetlenia print dialogu dla lepszej kontroli podczas drukowania. Metoda ShowPrintDialogAsync może być również użyta do drukowania asynchronicznego.
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
3. Dostosuj ustawienia drukowania
IronPrint oferuje różne print ustawienia, które pozwalają na szczegółową kontrolę nad drukowaniem dokumentu.
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
Aby lepiej zrozumieć wykorzystywane klasy i metody, proszę odwiedź stronę Dokumentacja API.
Wnioski
Drukowanie listy w C# obejmuje wybór odpowiedniej metody w zależności od złożoności danych i pożądanego wyniku. Niezależnie od tego, czy używasz prostego loopu, String.Join(), LINQ, czy dostosowujesz metodę ToString() dla niestandardowych obiektów, zrozumienie tych podejść pozwala skutecznie wyświetlać zawartość list w aplikacjach C#. Eksperymentuj z tymi technikami i wybierz tę, która najlepiej pasuje do twojego konkretnego przypadku użycia.
IronPrint to twoja biblioteka do drukowania, jeśli chodzi o dokładność, łatwość użycia i szybkość. Niezależnie od tego, czy budujesz WebApps, pracujesz z MAUI, Avalonia, czy cokolwiek związanego z .NET, IronPrint jest dla Ciebie. Aby uzyskać bardziej szczegółowe informacje o IronPrint, odwiedź tę stronę dokumentacji.
IronPrint to płatna biblioteka, ale dostępna jest darmowa wersja próbna. Pobierz bibliotekę z tutaj i spróbuj!
Często Zadawane Pytania
Jak wydrukować listę w języku C#?
Można użyć IronPrint do wydrukowania listy w języku C#, iterując po elementach listy za pomocą pętli foreach lub for i przekazując sformatowany wynik do IronPrint w celu wydrukowania.
Jakie są zalety korzystania z tablicy dynamicznej w języku C#?
Tablice dynamiczne, czyli listy, w języku C# zapewniają elastyczność, ponieważ ich rozmiar może się zwiększać lub zmniejszać. Są one częścią przestrzeni nazw System.Collections.Generic, umożliwiającej wydajną obsługę i manipulację kolekcjami.
Jak odwrócić listę w języku C# w celu wydrukowania?
Aby wydrukować listę w odwrotnej kolejności, można użyć metody Reverse lub OrderByDescending w LINQ, a następnie wydrukować odwróconą listę za pomocą IronPrint.
Jak sformatować listę jako ciąg znaków do wydruku?
Można użyć metody String.Join do połączenia elementów listy w jeden sformatowany ciąg znaków z określonym separatorem. Ten sformatowany ciąg znaków można następnie wydrukować za pomocą IronPrint.
Jaka jest rola metody ToString w drukowaniu obiektów niestandardowych?
Przepisując metodę ToString, można zdefiniować sposób reprezentacji instancji obiektów niestandardowych jako ciągów znaków, co poprawia czytelność podczas drukowania za pomocą IronPrint.
Jak mogę filtrować i drukować określone elementy z listy w języku C#?
Metody LINQ, takie jak Where, mogą być używane do filtrowania i wybierania określonych elementów z listy. Przefiltrowane wyniki można następnie wydrukować za pomocą IronPrint.
Jak zainstalować bibliotekę drukowania dla .NET?
IronPrint można zainstalować za pomocą konsoli NuGet Package Manager Console, wpisując polecenie Install-Package IronPrint, lub poprzez menedżera pakietów NuGet w Visual Studio.
Jakie funkcje oferuje IronPrint for .NET?
IronPrint oferuje kompatybilność międzyplatformową, obsługę różnych formatów dokumentów, ciche drukowanie, okna dialogowe drukowania oraz konfigurowalne ustawienia drukowania, co czyni go doskonałym wyborem dla programistów .NET.




