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
.
If you want to learn more about Dynamic Arrays
check the Introduction to Programming Course read more
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:
Count Property
The Count
property returns the number of elements in the list:
int count = numbers.Count; // count 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
Calculate the sum of the elements in 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 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}");
Filter elements from a list
In this example, the FindAll
method is used to filter even elements from a list.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Declare the list with numbers
List<int> evenNumbers = numbers.FindAll(number => number % 2 == 0); // Filters even numbers
Console.WriteLine("Even numbers:");
foreach (int number in evenNumbers)
{
Console.WriteLine(number); // Prints each even number
}
Find 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 numbers
int max = numbers.Max(); // Finds the maximum value
Console.WriteLine($"The maximum value is: {max}");
Sort 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 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
}
Count 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 numbers
int counter = numbers.Count(number => number > 3); // Counts elements greater than 3
Console.WriteLine($"There are {counter} elements greater than 3");
Remove 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 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
}