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
| Feature | Array | List |
|---|---|---|
| Size | Fixed | Dynamic |
| Add elements | Cannot | .Add() |
| Remove elements | Cannot | .Remove() |
| Performance | Slightly faster | More flexible |
| Use case | Fixed collections | When size changes |
Creating Lists
csharp1using System.Collections.Generic;23// Empty list4List<int> numbers = new List<int>();56// List with initial values7List<string> names = new List<string> { "Alice", "Bob", "Charlie" };89// Using var (type inferred)10var scores = new List<double> { 85.5, 92.0, 78.5 };1112// From array13int[] array = { 1, 2, 3, 4, 5 };14List<int> fromArray = new List<int>(array);15// Or: var fromArray = array.ToList();
Adding Elements
Add (single element)
csharp1List<string> fruits = new List<string>();23fruits.Add("Apple");4fruits.Add("Banana");5fruits.Add("Cherry");6// List: { "Apple", "Banana", "Cherry" }
AddRange (multiple elements)
csharp1List<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)
csharp1List<string> names = new List<string> { "Alice", "Charlie" };2names.Insert(1, "Bob"); // Insert at index 13// List: { "Alice", "Bob", "Charlie" }
Accessing Elements
csharp1List<string> colors = new List<string> { "Red", "Green", "Blue" };23// By index4string first = colors[0]; // "Red"5string last = colors[^1]; // "Blue" (C# 8+)67// Modify by index8colors[1] = "Yellow";9// List: { "Red", "Yellow", "Blue" }1011// Count property12int count = colors.Count; // 3
Removing Elements
Remove (by value)
csharp1List<string> names = new List<string> { "Alice", "Bob", "Charlie", "Bob" };23names.Remove("Bob"); // Removes FIRST occurrence4// List: { "Alice", "Charlie", "Bob" }
RemoveAt (by index)
csharp1List<int> numbers = new List<int> { 10, 20, 30, 40 };2numbers.RemoveAt(1); // Remove element at index 13// List: { 10, 30, 40 }
RemoveAll (by condition)
csharp1List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };2numbers.RemoveAll(n => n % 2 == 0); // Remove all even numbers3// List: { 1, 3, 5, 7 }
Clear (remove all)
csharp1List<string> items = new List<string> { "A", "B", "C" };2items.Clear();3// List is now empty, Count = 0
Searching
csharp1List<string> fruits = new List<string>2 { "Apple", "Banana", "Cherry", "Banana" };34// Contains5bool hasBanana = fruits.Contains("Banana"); // true67// IndexOf / LastIndexOf8int firstIndex = fruits.IndexOf("Banana"); // 19int lastIndex = fruits.LastIndexOf("Banana"); // 31011// Find (returns first match)12string found = fruits.Find(f => f.StartsWith("C")); // "Cherry"1314// FindAll (returns all matches)15List<string> withB = fruits.FindAll(f => f.StartsWith("B"));16// { "Banana", "Banana" }1718// FindIndex19int index = fruits.FindIndex(f => f.Length > 5); // 1 ("Banana")2021// Exists22bool hasLongName = fruits.Exists(f => f.Length > 5); // true
Sorting and Ordering
csharp1List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };23// Sort ascending4numbers.Sort();5// { 1, 2, 5, 8, 9 }67// Reverse8numbers.Reverse();9// { 9, 8, 5, 2, 1 }1011// Sort with custom comparison12List<string> names = new List<string> { "Charlie", "Alice", "Bob" };13names.Sort(); // Alphabetical: { "Alice", "Bob", "Charlie" }1415// Sort by string length16names.Sort((a, b) => a.Length.CompareTo(b.Length));17// { "Bob", "Alice", "Charlie" }
Iterating
csharp1List<string> items = new List<string> { "A", "B", "C" };23// foreach4foreach (string item in items)5{6 Console.WriteLine(item);7}89// for loop (when you need index)10for (int i = 0; i < items.Count; i++)11{12 Console.WriteLine($"{i}: {items[i]}");13}1415// ForEach method16items.ForEach(item => Console.WriteLine(item));
Converting
csharp1List<int> list = new List<int> { 1, 2, 3, 4, 5 };23// To array4int[] array = list.ToArray();56// From array7var newList = array.ToList();89// To string10string joined = string.Join(", ", list); // "1, 2, 3, 4, 5"
Useful Properties and Methods
csharp1List<int> numbers = new List<int> { 3, 1, 4, 1, 5, 9 };23// Properties4int count = numbers.Count; // 65int capacity = numbers.Capacity; // Usually >= Count67// Methods8numbers.TrimExcess(); // Minimize memory usage910// Check if empty11bool isEmpty = numbers.Count == 0;1213// Copy portion14List<int> subList = numbers.GetRange(1, 3); // { 1, 4, 1 }
Practical Example: Todo List
csharp1List<string> todos = new List<string>();23while (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: ");1213 string choice = Console.ReadLine() ?? "";1415 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;2627 case "2":28 if (todos.Count == 0)29 {30 Console.WriteLine("No tasks!");31 }32 else33 {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;4142 case "3":43 if (todos.Count == 0)44 {45 Console.WriteLine("No tasks to complete!");46 }47 else48 {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 else58 {59 Console.WriteLine("Invalid number!");60 }61 }62 break;6364 case "4":65 todos.Clear();66 Console.WriteLine("All tasks cleared!");67 break;6869 case "5":70 Console.WriteLine("Goodbye!");71 return;7273 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
Countproperty (notLengthlike arrays) - Convert between arrays and lists with
ToArray()andToList()
Now let's practice with hands-on workshops!