Language: EN

csharp-que-son-listas

What are Lists and how to use them in C#

A List is a generic collection that implements an array with dynamic size. It is one of the data structures that you will use most frequently.

Unlike arrays, lists allow for dynamic manipulation of their elements (i.e., we can add and remove elements, 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 the list is declared, before we can use it, we must initialize it. To do this, we need to create a new List and assign it to the variable we declared earlier.

Alternatively, we can do this at the same time we declare our List. Like this:

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

// equivalent
var numbers = new List<int>();
List<int> numbers = new ();

Initializing Lists

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

// 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 List Usage

Accessing List Elements

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 List Elements

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);

Additionally, 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

Clearing the Entire List

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

Inserting 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 take a look at some of them:

Count Property

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

int quantity = numbers.Count; // quantity 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 List Elements

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 }; // We declare the list with the numbers
int sum = 0; // Variable to store the sum of the elements

foreach (int number in numbers)
{
    sum += number; // Adds 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 }; // We 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 }; // We 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 }; // We declare the list with the unordered 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 }; // We 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 }; // We 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
}