← Back to course: C# from scratch

List<T>, foreach and working with collections

Video coming soon

Arrays have a limit: their size does not change. In real life lists grow and shrink: the shopping list, the orders of a store, the expenses of the month. For that C# offers List<T>, a dynamic-size collection. The T is a generic type: List<int> is a list of integers, List<string> a list of texts. A list keeps the order in which you added the elements and is accessed by index, just like an array, but with many extra methods.

The main methods

Add appends to the end, Insert puts an element at a position, Remove deletes the first occurrence of a value, RemoveAt deletes by index and Clear empties the list. To query you have Count (how many elements there are; in lists it is called Count, not Length), Contains, IndexOf, and the helpers Sort and Reverse. There are also more powerful methods that take a condition, such as Find, Exists and RemoveAll; you will see them in more depth when we reach LINQ. Since C# 12 you can create a list with brackets: List<int> list = [1, 2, 3];.

csharp
List<string> shopping = new List<string>();
shopping.Add("milk");
shopping.Add("bread");
shopping.Add("eggs");
shopping.Insert(1, "coffee");           // milk, coffee, bread, eggs

Console.WriteLine(shopping.Count);      // 4
Console.WriteLine(shopping[2]);         // bread
Console.WriteLine(shopping.Contains("eggs")); // True

shopping.Remove("bread");               // by value
shopping.RemoveAt(0);                   // by index: removes milk
Console.WriteLine(string.Join(", ", shopping)); // coffee, eggs

List<int> numbers = [5, 3, 8, 1];
numbers.Sort();
Console.WriteLine(string.Join(" ", numbers));   // 1 3 5 8

The foreach loop

When you only want to go through all the elements, without needing the index, foreach is the cleanest and safest option: foreach (var item in collection) { ... }. There is no risk of off-by-one errors, and it works with arrays, lists and almost any collection. There is an important rule: inside a foreach you cannot add or remove elements of the collection being traversed, because the list would change while it is read and C# throws an InvalidOperationException. If you need to delete while going through, use RemoveAll with a condition, or traverse a copy, or use a backwards for loop. You also cannot change the loop variable: item is read-only.

csharp
List<decimal> expenses = [12.5m, 80m, 7.25m, 150m, 33m];

decimal total = 0;
foreach (decimal expense in expenses)
{
    total += expense;
}
Console.WriteLine($"Total: {total}");         // Total: 282.75

// remove all small expenses safely
int removed = expenses.RemoveAll(e => e < 20);
Console.WriteLine($"Removed {removed}, left {expenses.Count}"); // Removed 2, left 3

// for loop when you need the index
for (int i = 0; i < expenses.Count; i++)
{
    Console.WriteLine($"{i + 1}. {expenses[i]}");
}

// foreach (var e in expenses) { expenses.Remove(e); } // InvalidOperationException

Test what you learned

Question 1 of 2

Which property gives the number of elements of a List<T>?

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →