Skip to footer content
.NET HELP

C# List (How it Works For Developers)

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.

Frequently Asked Questions

How can I create a List in C#?

To create a List in C#, you need to include the System.Collections.Generic namespace. You can then declare a List by specifying the data type within angle brackets. For example: Listnumbers = new List();

What methods are used to add elements to a C# List?

Elements can be added to a C# List using the Add() method for individual elements and AddRange() for adding a collection of elements.

How can I export a C# List to a PDF file?

To export a C# List to a PDF file, you can use the IronPDF library. Convert your List data into an HTML table format and then render it as a PDF using IronPDF.

What is the best way to sort a C# List?

You can sort a C# List in ascending order using the Sort() method. To sort in descending order, you can use Sort() with a custom comparison delegate.

How do you access elements in a C# List?

Elements in a C# List can be accessed using their index, similar to arrays. Lists are zero-based indexed, so you can use an element's position in the List to retrieve it.

What options are available to remove elements from a C# List?

You can remove elements from a C# List using the Remove() method for specific elements, RemoveAt() for a specific index, or Clear() to remove all elements.

How can LINQ be utilized with C# Lists?

LINQ can be used with C# Lists to perform powerful queries and transformations, such as filtering, mapping, and finding minimum or maximum values efficiently.

How can I convert a List to an array in C#?

You can convert a C# List to an array using the ToArray() method, which creates a new array containing the elements of the List.

What are some common use cases for C# Lists?

C# Lists are commonly used for managing dynamic collections of data, performing complex queries with LINQ, and generating reports or documents using libraries like IronPDF.

How do you iterate over elements in a C# List?

You can iterate over elements in a C# List using foreach loops for simple iteration or for loops when you need the index.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of ...Read More