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 most frequently used data structures.

Unlike arrays, lists allow dynamic manipulation of their elements (that is, 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 need to initialize it. To do this, we must create a new List and assign it to the variable we previously declared.

Alternatively, we can do it 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 values known at compile time, we can do it 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

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

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

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

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

:::::::

Practical Examples