12 minlesson

Lists

Lists

The List<T> collection is a dynamic array that can grow and shrink. It's one of the most commonly used collection types in C#.

List vs Array

FeatureArrayList
SizeFixedDynamic
Add elementsCannot.Add()
Remove elementsCannot.Remove()
PerformanceSlightly fasterMore flexible
Use caseFixed collectionsWhen size changes

Creating Lists

csharp
1using System.Collections.Generic;
2
3// Empty list
4List<int> numbers = new List<int>();
5
6// List with initial values
7List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
8
9// Using var (type inferred)
10var scores = new List<double> { 85.5, 92.0, 78.5 };
11
12// From array
13int[] array = { 1, 2, 3, 4, 5 };
14List<int> fromArray = new List<int>(array);
15// Or: var fromArray = array.ToList();

Adding Elements

Add (single element)

csharp
1List<string> fruits = new List<string>();
2
3fruits.Add("Apple");
4fruits.Add("Banana");
5fruits.Add("Cherry");
6// List: { "Apple", "Banana", "Cherry" }

AddRange (multiple elements)

csharp
1List<int> numbers = new List<int> { 1, 2, 3 };
2numbers.AddRange(new[] { 4, 5, 6 });
3// List: { 1, 2, 3, 4, 5, 6 }

Insert (at specific position)

csharp
1List<string> names = new List<string> { "Alice", "Charlie" };
2names.Insert(1, "Bob"); // Insert at index 1
3// List: { "Alice", "Bob", "Charlie" }

Accessing Elements

csharp
1List<string> colors = new List<string> { "Red", "Green", "Blue" };
2
3// By index
4string first = colors[0]; // "Red"
5string last = colors[^1]; // "Blue" (C# 8+)
6
7// Modify by index
8colors[1] = "Yellow";
9// List: { "Red", "Yellow", "Blue" }
10
11// Count property
12int count = colors.Count; // 3

Removing Elements

Remove (by value)

csharp
1List<string> names = new List<string> { "Alice", "Bob", "Charlie", "Bob" };
2
3names.Remove("Bob"); // Removes FIRST occurrence
4// List: { "Alice", "Charlie", "Bob" }

RemoveAt (by index)

csharp
1List<int> numbers = new List<int> { 10, 20, 30, 40 };
2numbers.RemoveAt(1); // Remove element at index 1
3// List: { 10, 30, 40 }

RemoveAll (by condition)

csharp
1List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
2numbers.RemoveAll(n => n % 2 == 0); // Remove all even numbers
3// List: { 1, 3, 5, 7 }

Clear (remove all)

csharp
1List<string> items = new List<string> { "A", "B", "C" };
2items.Clear();
3// List is now empty, Count = 0

Searching

csharp
1List<string> fruits = new List<string>
2 { "Apple", "Banana", "Cherry", "Banana" };
3
4// Contains
5bool hasBanana = fruits.Contains("Banana"); // true
6
7// IndexOf / LastIndexOf
8int firstIndex = fruits.IndexOf("Banana"); // 1
9int lastIndex = fruits.LastIndexOf("Banana"); // 3
10
11// Find (returns first match)
12string found = fruits.Find(f => f.StartsWith("C")); // "Cherry"
13
14// FindAll (returns all matches)
15List<string> withB = fruits.FindAll(f => f.StartsWith("B"));
16// { "Banana", "Banana" }
17
18// FindIndex
19int index = fruits.FindIndex(f => f.Length > 5); // 1 ("Banana")
20
21// Exists
22bool hasLongName = fruits.Exists(f => f.Length > 5); // true

Sorting and Ordering

csharp
1List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };
2
3// Sort ascending
4numbers.Sort();
5// { 1, 2, 5, 8, 9 }
6
7// Reverse
8numbers.Reverse();
9// { 9, 8, 5, 2, 1 }
10
11// Sort with custom comparison
12List<string> names = new List<string> { "Charlie", "Alice", "Bob" };
13names.Sort(); // Alphabetical: { "Alice", "Bob", "Charlie" }
14
15// Sort by string length
16names.Sort((a, b) => a.Length.CompareTo(b.Length));
17// { "Bob", "Alice", "Charlie" }

Iterating

csharp
1List<string> items = new List<string> { "A", "B", "C" };
2
3// foreach
4foreach (string item in items)
5{
6 Console.WriteLine(item);
7}
8
9// for loop (when you need index)
10for (int i = 0; i < items.Count; i++)
11{
12 Console.WriteLine($"{i}: {items[i]}");
13}
14
15// ForEach method
16items.ForEach(item => Console.WriteLine(item));

Converting

csharp
1List<int> list = new List<int> { 1, 2, 3, 4, 5 };
2
3// To array
4int[] array = list.ToArray();
5
6// From array
7var newList = array.ToList();
8
9// To string
10string joined = string.Join(", ", list); // "1, 2, 3, 4, 5"

Useful Properties and Methods

csharp
1List<int> numbers = new List<int> { 3, 1, 4, 1, 5, 9 };
2
3// Properties
4int count = numbers.Count; // 6
5int capacity = numbers.Capacity; // Usually >= Count
6
7// Methods
8numbers.TrimExcess(); // Minimize memory usage
9
10// Check if empty
11bool isEmpty = numbers.Count == 0;
12
13// Copy portion
14List<int> subList = numbers.GetRange(1, 3); // { 1, 4, 1 }

Practical Example: Todo List

csharp
1List<string> todos = new List<string>();
2
3while (true)
4{
5 Console.WriteLine("\n=== TODO LIST ===");
6 Console.WriteLine("1. Add task");
7 Console.WriteLine("2. View tasks");
8 Console.WriteLine("3. Complete task");
9 Console.WriteLine("4. Clear all");
10 Console.WriteLine("5. Exit");
11 Console.Write("Choice: ");
12
13 string choice = Console.ReadLine() ?? "";
14
15 switch (choice)
16 {
17 case "1":
18 Console.Write("Enter task: ");
19 string task = Console.ReadLine() ?? "";
20 if (!string.IsNullOrWhiteSpace(task))
21 {
22 todos.Add(task);
23 Console.WriteLine("Task added!");
24 }
25 break;
26
27 case "2":
28 if (todos.Count == 0)
29 {
30 Console.WriteLine("No tasks!");
31 }
32 else
33 {
34 Console.WriteLine("\nYour tasks:");
35 for (int i = 0; i < todos.Count; i++)
36 {
37 Console.WriteLine($" {i + 1}. {todos[i]}");
38 }
39 }
40 break;
41
42 case "3":
43 if (todos.Count == 0)
44 {
45 Console.WriteLine("No tasks to complete!");
46 }
47 else
48 {
49 Console.Write("Task number to complete: ");
50 if (int.TryParse(Console.ReadLine(), out int num) &&
51 num >= 1 && num <= todos.Count)
52 {
53 string completed = todos[num - 1];
54 todos.RemoveAt(num - 1);
55 Console.WriteLine($"Completed: {completed}");
56 }
57 else
58 {
59 Console.WriteLine("Invalid number!");
60 }
61 }
62 break;
63
64 case "4":
65 todos.Clear();
66 Console.WriteLine("All tasks cleared!");
67 break;
68
69 case "5":
70 Console.WriteLine("Goodbye!");
71 return;
72
73 default:
74 Console.WriteLine("Invalid choice!");
75 break;
76 }
77}

Summary

In this lesson, you learned:

  • List<T> is a dynamic array that can grow and shrink
  • Add elements with Add(), AddRange(), Insert()
  • Remove with Remove(), RemoveAt(), RemoveAll(), Clear()
  • Search with Contains(), Find(), IndexOf()
  • Sort with Sort(), Reverse()
  • Use Count property (not Length like arrays)
  • Convert between arrays and lists with ToArray() and ToList()

Now let's practice with hands-on workshops!