Language: EN

csharp-que-son-listas

What are Lists and how to use them in C#

A List is a generic collection that implements a dynamically expanded array. It is one of the data structures that you will use most frequently.

Unlike arrays, lists allow dynamic manipulation of their elements, including adding and removing elements without needing to define a fixed size at the beginning.

The class List<T> in the namespace System.Collections.Generic allows you to create lists of any type specified by the type parameter T.

Declaring lists

To declare a list in C#, the following syntax is used:

List<type> listName;

For example, to declare a list of integers:

List<int> numbers;

Creating the list

Once declared, before we can use it we must initialize it, before we can use it. To do this we must create a new List, and assign it to the variable we have previously declared.

Or, alternatively, we can do it at the same time we declare our List. Like this:

List<int> numbers = new List<int>();

Initializing lists

Alternatively, if we want to initialize the list with a series of known values at compile time, we can do this using the semantic initializer [].

// recommended syntax
List<int> numbers = [ 1, 2, 3, 4, 5 ];

// equivalent to this
List<int> numbers = new () { 1, 2, 3, 4, 5 };
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };

Previously there were other ways

Basic use of list

Accessing elements of a list

The elements of a list can be accessed by indices, starting from 0:

List<int> numbers = new List<int>();

int firstNumber = numbers[0]; // firstNumber will be 1

Modifying elements of a list

The elements of a list can be modified by assigning new values to specific indices:

numbers[1] = 20; // The second element of the list will now be 20

Adding elements to a list

To add elements to a list, the Add method is used:

numbers.Add(1);

In addition, we can add multiple elements at once using the AddRange() method:

list.AddRange(collection);

Where collection represents a collection of elements of the same type as the list.

Removing elements from a list

To remove an element from a list, we can use the Remove() method:

numbers.Remove(20); // Removes the first element with the value 20

It is also possible to remove an element based on its index using the RemoveAt() method:

numbers.RemoveAt(0); // Removes the first element

Clear the entire list

numbers.Clear(); // Removes all elements from the list

Insert elements at a specific position

To insert an element at a specific position in the list, the Insert method is used:

numbers.Insert(1, 15); // Inserts the number 15 at position 1

Useful properties and methods of List<T>

Lists in C# offer a wide range of operations that allow us to manipulate and access their elements efficiently. Let’s see some of them:

Count Property

The Count property returns the number of elements in the list:

int amount = numbers.Count; // amount will be the number of elements in the list

Contains Method

The Contains method checks if a specific value is present in the list:

bool contains = numbers.Contains(3); // contains will be true if the number 3 is in the list

IndexOf Method

The IndexOf method returns the index of the first occurrence of a specific value in the list:

int index = numbers.IndexOf(3); // index will be the position of the number 3 in the list

Sort Method

The Sort method sorts the elements of the list:

numbers.Sort(); // Sorts the elements in ascending order

Reverse Method

The Reverse method reverses the order of the elements in the list:

numbers.Reverse(); // Reverses the order of the elements in the list

Practical examples

Calculating the sum of the elements of a list

In this example, a foreach loop is used to calculate the sum of the elements in a list.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with the numbers
int sum = 0; // Variable to store the sum of the elements

foreach (int number in numbers)
{
    sum += number; // Add each element of the list to 'sum'
}

Console.WriteLine($"The sum of the elements is: {sum}");

Filtering elements from a list

In this example, the FindAll method is used to filter the even elements from a list.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with the numbers
List<int> evenNumbers = numbers.FindAll(number => number % 2 == 0); // Filters the even numbers

Console.WriteLine("Even numbers:");
foreach (int number in evenNumbers)
{
    Console.WriteLine(number); // Prints each even number
}

Finding the maximum value in a list

In this example, the Max method is used to find the maximum value in a list.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with the numbers
int maximum = numbers.Max(); // Finds the maximum value

Console.WriteLine($"The maximum value is: {maximum}");

Sorting the elements of a list

In this example, the Sort method is used to sort the elements of a list in ascending order.

List<int> numbers = new List<int> { 5, 3, 1, 4, 2 }; // Declare the list with the unsorted numbers
numbers.Sort(); // Sorts the list in ascending order

Console.WriteLine("Sorted numbers:");
foreach (int number in numbers)
{
    Console.WriteLine(number); // Prints each number in order
}

Counting how many elements meet a condition

In this example, the Count method is used to count how many elements in a list are greater than a specific value.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with the numbers
int counter = numbers.Count(number => number > 3); // Counts the elements greater than 3

Console.WriteLine($"There are {counter} elements greater than 3");

Removing elements from a list

In this example, the RemoveAll method is used to remove all odd elements from a list.

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with the numbers
numbers.RemoveAll(number => number % 2 != 0); // Removes all odd numbers

Console.WriteLine("Remaining numbers:");
foreach (int number in numbers)
{
    Console.WriteLine(number); // Prints the remaining numbers
}