Zum Fußzeileninhalt springen
.NET HILFE

C# Liste (Wie es für Entwickler funktioniert)

Lists are versatile and dynamic data structures used to store and manipulate collections of data in C#. They are part of the System.Collections.Generic namespace, which provides a range of powerful, type-safe collection classes and strongly typed objects. This beginner-friendly tutorial will guide you through the basics of using C# Lists, including how to create/add elements, access specified indices or first occurrences, modify specified elements, and remove elements, as well as some common use cases.

Creating Lists

To start using the List class, you first need to include the System.Collections.Generic namespace in your code:

using System.Collections.Generic;
using System.Collections.Generic;
Imports System.Collections.Generic
$vbLabelText   $csharpLabel

After adding the generic namespace, create a new List object by specifying the data type of all the elements you want to store inside angular brackets (< >). Here's an example of how to create a list of integers:

List<int> numbers = new List<int>();
List<int> numbers = new List<int>();
Dim numbers As New List(Of Integer)()
$vbLabelText   $csharpLabel

You can also initialize a list with some initial values or define it by the specified collection like this:

List<string> fruits = new List<string> { "apple", "banana", "cherry" };
List<string> fruits = new List<string> { "apple", "banana", "cherry" };
Dim fruits As New List(Of String) From {"apple", "banana", "cherry"}
$vbLabelText   $csharpLabel

We can also specify the default initial capacity of the list. The specified initial capacity is the default maximum capacity of the list.

Methods of List

Adding Number of Elements to a List

To add elements to your List, use the Add() method:

numbers.Add(1);     // Adds first element
numbers.Add(2);
numbers.Add(3);
numbers.Add(1);     // Adds first element
numbers.Add(2);
numbers.Add(3);
numbers.Add(1) ' Adds first element
numbers.Add(2)
numbers.Add(3)
$vbLabelText   $csharpLabel

You can also add a range of elements from a specified collection to the list using the AddRange method:

List<int> moreNumbers = new List<int> { 4, 5, 6 };
numbers.AddRange(moreNumbers);
List<int> moreNumbers = new List<int> { 4, 5, 6 };
numbers.AddRange(moreNumbers);
Dim moreNumbers As New List(Of Integer) From {4, 5, 6}
numbers.AddRange(moreNumbers)
$vbLabelText   $csharpLabel

Accessing List Elements

You can access individual elements of a list using an index, just like with arrays:

string firstFruit = fruits[0];          // "apple"
string secondFruit = fruits[1];         // "banana"
string firstFruit = fruits[0];          // "apple"
string secondFruit = fruits[1];         // "banana"
Dim firstFruit As String = fruits(0) ' "apple"
Dim secondFruit As String = fruits(1) ' "banana"
$vbLabelText   $csharpLabel

Keep in mind that lists are zero-based indexed, so the first element has an index of 0. The above example will store the element in the string if it exists.

Modifying List Elements

To modify an element in a list, simply assign a new value to the element at the desired index, keeping in mind the zero-based index:

fruits[1] = "blueberry";
fruits[1] = "blueberry";
fruits(1) = "blueberry"
$vbLabelText   $csharpLabel

Now, the second element in the fruits list is "blueberry" instead of "banana".

Removing Elements from a List

To remove an element from a list, you can use the Remove method, which removes the first occurrence of a specified element:

fruits.Remove("apple");
fruits.Remove("apple");
fruits.Remove("apple")
$vbLabelText   $csharpLabel

Alternatively, you can use the RemoveAt method to remove an element at the specified index:

fruits.RemoveAt(0);
fruits.RemoveAt(0);
fruits.RemoveAt(0)
$vbLabelText   $csharpLabel

To remove all elements from a list, use the Clear method:

fruits.Clear();
fruits.Clear();
fruits.Clear()
$vbLabelText   $csharpLabel

Finding Elements in a List

You can use the Contains() method to check if a list contains a specific element:

bool containsApple = fruits.Contains("apple");  // true
bool containsApple = fruits.Contains("apple");  // true
Dim containsApple As Boolean = fruits.Contains("apple") ' true
$vbLabelText   $csharpLabel

To find the index of the first occurrence of an element, use the IndexOf method:

int appleIndex = fruits.IndexOf("apple");  // 0
int appleIndex = fruits.IndexOf("apple");  // 0
Dim appleIndex As Integer = fruits.IndexOf("apple") ' 0
$vbLabelText   $csharpLabel

If the element is not found, IndexOf returns -1.

Looping Through a List

To iterate through the elements in a list, you can use a foreach loop:

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
For Each fruit As String In fruits
	Console.WriteLine(fruit)
Next fruit
$vbLabelText   $csharpLabel

Alternatively, you can use a for loop with the Count property, which returns the number of elements in the list:

for (int i = 0; i < fruits.Count; i++)
{
    Console.WriteLine(fruits[i]);
}
for (int i = 0; i < fruits.Count; i++)
{
    Console.WriteLine(fruits[i]);
}
For i As Integer = 0 To fruits.Count - 1
	Console.WriteLine(fruits(i))
Next i
$vbLabelText   $csharpLabel

Sorting a List

To sort a list in ascending order, use the Sort method:

List<int> unsortedNumbers = new List<int> { 5, 2, 8, 1, 4 };
unsortedNumbers.Sort();

// Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
List<int> unsortedNumbers = new List<int> { 5, 2, 8, 1, 4 };
unsortedNumbers.Sort();

// Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
Dim unsortedNumbers As New List(Of Integer) From {5, 2, 8, 1, 4}
unsortedNumbers.Sort()

' Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
$vbLabelText   $csharpLabel

To sort a list in descending order, you can use the Sort method with a custom comparison:

unsortedNumbers.Sort((a, b) => b.CompareTo(a));

// Now, unsortedNumbers is { 8, 5, 4, 2, 1 }
unsortedNumbers.Sort((a, b) => b.CompareTo(a));

// Now, unsortedNumbers is { 8, 5, 4, 2, 1 }
unsortedNumbers.Sort(Function(a, b) b.CompareTo(a))

' Now, unsortedNumbers is { 8, 5, 4, 2, 1 }
$vbLabelText   $csharpLabel

For more complex sorting, you can implement a custom IComparer class or use LINQ (Language Integrated Query). The binary search algorithm works on sorted lists.

Using LINQ with Lists

LINQ allows you to perform powerful queries and transformations on collections, including lists. To use LINQ, you first need to include the System.Linq namespace in your code:

using System.Linq;
using System.Linq;
Imports System.Linq
$vbLabelText   $csharpLabel

Here are some examples of LINQ queries on a list:

Filtering a list

List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
Dim evenNumbers As List(Of Integer) = numbers.Where(Function(x) x Mod 2 = 0).ToList()
$vbLabelText   $csharpLabel

Mapping (transforming) Elements in a List

List<string> fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
List<string> fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
Dim fruitNamesUpperCase As List(Of String) = fruits.Select(Function(x) x.ToUpper()).ToList()
$vbLabelText   $csharpLabel

Finding the Minimum and Maximum Values in a List

int minValue = numbers.Min();
int maxValue = numbers.Max();
int minValue = numbers.Min();
int maxValue = numbers.Max();
Dim minValue As Integer = numbers.Min()
Dim maxValue As Integer = numbers.Max()
$vbLabelText   $csharpLabel

Converting a List to an Array

To convert a list to an array, you can use the ToArray method:

int[] numbersArray = numbers.ToArray();
int[] numbersArray = numbers.ToArray();
Dim numbersArray() As Integer = numbers.ToArray()
$vbLabelText   $csharpLabel

Exporting List Data to a PDF Using IronPDF

In this section, we will demonstrate how to export the data in a List to a PDF file using the IronPDF library. This can be helpful when you want to generate a report or a printable version of your data.

First, download and install the IronPDF NuGet package to your project:

Install-Package IronPdf

Next, include the IronPdf namespace in your code:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

Now, let's create a simple function that converts a List of strings into an HTML table and then exports it to a PDF file:

using System.Collections.Generic;
using System.Text;
using IronPdf;

void ExportListToPdf(List<string> data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("<table><tr><th>Item</th></tr>");

    foreach (string item in data)
    {
        htmlBuilder.Append($"<tr><td>{item}</td></tr>");
    }

    htmlBuilder.Append("</table>");

    // Convert the HTML table to a PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());

    // Save the PDF to the specified file path
    pdf.SaveAs(pdfFilePath);
}
using System.Collections.Generic;
using System.Text;
using IronPdf;

void ExportListToPdf(List<string> data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("<table><tr><th>Item</th></tr>");

    foreach (string item in data)
    {
        htmlBuilder.Append($"<tr><td>{item}</td></tr>");
    }

    htmlBuilder.Append("</table>");

    // Convert the HTML table to a PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());

    // Save the PDF to the specified file path
    pdf.SaveAs(pdfFilePath);
}
Imports System.Collections.Generic
Imports System.Text
Imports IronPdf

Private Sub ExportListToPdf(ByVal data As List(Of String), ByVal pdfFilePath As String)
	' Create an HTML table from the list data
	Dim htmlBuilder As New StringBuilder()
	htmlBuilder.Append("<table><tr><th>Item</th></tr>")

	For Each item As String In data
		htmlBuilder.Append($"<tr><td>{item}</td></tr>")
	Next item

	htmlBuilder.Append("</table>")

	' Convert the HTML table to a PDF using IronPDF
	Dim renderer = New ChromePdfRenderer()
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlBuilder.ToString())

	' Save the PDF to the specified file path
	pdf.SaveAs(pdfFilePath)
End Sub
$vbLabelText   $csharpLabel

To use this function, simply call it with your list and the desired PDF file path:

List<string> fruits = new List<string> { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
List<string> fruits = new List<string> { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
Dim fruits As New List(Of String) From {"apple", "banana", "cherry"}
ExportListToPdf(fruits, "Fruits.pdf")
$vbLabelText   $csharpLabel

This will generate a PDF file named "Fruits.pdf" containing a table with the list of fruits by converting HTML to PDF with IronPDF. You can modify the ExportListToPdf function to suit your needs, such as adding custom styling to the HTML table or additional content to the PDF.

C# List (How It Works For Developers) Figure 1 - HTML to PDF

Conclusion

In this beginner-friendly tutorial, we covered the basics of using C# Lists and demonstrated how to integrate IronPDF to export List data to a PDF file. By incorporating IronPDF into your projects, you can easily generate reports, invoices, or other printable documents from your C# projects.

IronPDF offers a free trial, allowing you to test its capabilities before committing to a purchase.

Häufig gestellte Fragen

Wie kann ich eine Liste in C# erstellen?

Um eine Liste in C# zu erstellen, müssen Sie den Namespace System.Collections.Generic einbinden. Sie können dann eine Liste deklarieren, indem Sie den Datentyp in spitzen Klammern angeben. Zum Beispiel: List numbers = new List();

Welche Methoden fügen Elemente zu einer C#-Liste hinzu?

Elemente können zu einer C#-Liste mit der Add()-Methode für einzelne Elemente und AddRange() zum Hinzufügen einer Sammlung von Elementen hinzugefügt werden.

Wie kann ich eine C#-Liste in eine PDF-Datei exportieren?

Um eine C#-Liste in eine PDF-Datei zu exportieren, können Sie die IronPDF-Bibliothek verwenden. Konvertieren Sie Ihre Listendaten in ein HTML-Tabellenformat und rendern Sie es dann als PDF mit IronPDF.

Was ist der beste Weg, um eine C#-Liste zu sortieren?

Sie können eine C#-Liste in aufsteigender Reihenfolge mit der Sort()-Methode sortieren. Um in absteigender Reihenfolge zu sortieren, können Sie Sort() mit einem benutzerdefinierten Vergleichsdelegaten verwenden.

Wie greift man auf Elemente in einer C#-Liste zu?

Auf Elemente in einer C#-Liste kann mit ihrem Index zugegriffen werden, ähnlich wie bei Arrays. Listen sind nullbasiert indiziert, sodass Sie die Position eines Elements in der Liste verwenden können, um darauf zuzugreifen.

Welche Optionen gibt es, um Elemente aus einer C#-Liste zu entfernen?

Sie können Elemente aus einer C#-Liste mit Remove() für bestimmte Elemente, RemoveAt() für einen Index oder Clear() entfernen.

Wie kann LINQ mit C#-Listen genutzt werden?

LINQ kann mit C#-Listen verwendet werden, um leistungsstarke Abfragen und Transformationen durchzuführen, wie z.B. Filtern, Mapping und effizientes Finden von Minimal- oder Maximalwerten.

Wie kann ich eine Liste in ein Array in C# umwandeln?

Sie können eine C#-Liste mit der ToArray()-Methode in ein Array umwandeln.

Was sind einige gängige Anwendungsfälle für C#-Listen?

C#-Listen werden häufig zum Verwalten dynamischer Datensammlungen, zum Durchführen komplexer Abfragen mit LINQ und zum Erstellen von Berichten oder Dokumenten mit Bibliotheken wie IronPDF verwendet.

Wie iteriert man über Elemente in einer C#-Liste?

Sie können über Elemente in einer C#-Liste mit foreach-Schleifen für einfache Iterationen oder for-Schleifen iterieren, wenn Sie den Index benötigen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen