.NET HELP

C# List (How it Works For Developers)

Published June 6, 2023
Share:

Introduction

Lists are versatile and dynamic data structures used to store and manipulate collections of data in C#. Lists 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 index or first occurrence, modify specified element, and remove elements, as well as some common use cases.

Creating Lists

To start using 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
VB   C#

After adding a 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 numbers = new List();
List numbers = new List();
Dim numbers As New List()
VB   C#

You can also insert elements to a list with some initial values or defined by the specified collection like this:

List fruits = new List { "apple", "banana", "cherry" };
List fruits = new List { "apple", "banana", "cherry" };
Dim fruits As New List From {"apple", "banana", "cherry"}
VB   C#

We can also specify default initial capacity of the list in the above example. 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 internal data structure 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)
VB   C#

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

List moreNumbers = new List { 4, 5, 6 };
numbers.AddRange(moreNumbers);
List moreNumbers = new List { 4, 5, 6 };
numbers.AddRange(moreNumbers);
Dim moreNumbers As New List From {4, 5, 6}
numbers.AddRange(moreNumbers)
VB   C#

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

Keep in mind that the lists are zero based index, so the first element has an index of 0. If element exists, above example will store that element to the string.

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

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

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

fruits.RemoveAt(0);
fruits.RemoveAt(0);
fruits.RemoveAt(0)
VB   C#

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

fruits.Clear();
fruits.Clear();
fruits.Clear()
VB   C#

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

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

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. Using foreach loop, you can also access all the elements of the array.

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

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

Sorting a List

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

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

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

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

' Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
VB   C#

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

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

For more complex sorting, you can implement a custom IComparer class or use LINQ (Language INtegrated Query). 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 class program code:

using System.Linq;
using System.Linq;
Imports System.Linq
VB   C#

Here are some examples of LINQ queries on a list:

Filtering a list

List evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
List evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
Dim evenNumbers As List = numbers.Where(Function(x) x Mod 2 = 0).ToList()
VB   C#

Mapping (transforming) Elements in a List

List fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
List fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
Dim fruitNamesUpperCase As List = fruits.Select(Function(x) x.ToUpper()).ToList()
VB   C#

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

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

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

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 IronPdf;
using System.Text;
void ExportListToPdf(List data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("Item");

    foreach (string item in data)
    {
        htmlBuilder.Append($"{item}");
    }

    htmlBuilder.Append("");

    // Convert the HTML table to a PDF using IronPDF specified object
    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 IronPdf;
using System.Text;
void ExportListToPdf(List data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("Item");

    foreach (string item in data)
    {
        htmlBuilder.Append($"{item}");
    }

    htmlBuilder.Append("");

    // Convert the HTML table to a PDF using IronPDF specified object
    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 IronPdf
Imports System.Text
Private Sub ExportListToPdf(ByVal data As List, ByVal pdfFilePath As String)
	' Create an HTML table from the list data
	Dim htmlBuilder As New StringBuilder()
	htmlBuilder.Append("Item")

	For Each item As String In data
		htmlBuilder.Append($"{item}")
	Next item

	htmlBuilder.Append("")

	' Convert the HTML table to a PDF using IronPDF specified object
	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
VB   C#

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

List fruits = new List { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
List fruits = new List { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
Dim fruits As New List From {"apple", "banana", "cherry"}
ExportListToPdf(fruits, "Fruits.pdf")
VB   C#

This will generate a PDF file named "Fruits.pdf" containing a table with the default capacity list of fruits by converting HTML to PDF that matches the conditions defined. 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#

IronPDF offers a free trial, allowing you to test its capabilities before committing to a purchase. If you decide to continue using IronPDF after the trial period, licensing starts from $749, with multiple licensing options available to suit your needs.

< PREVIOUS
C# This (How it Works for Developers)
NEXT >
What is Visual Studio (How it Works for Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >