Site

List — C# List<T>

Tutorial S2  •  C# / Learn

S2.0 What This Teaches

This tutorial covers List<T>, C#'s general-purpose dynamic array:

S2.1 Creating and Initializing

// Empty list
var numbers = new List<int>();

// Collection initializer
var fruits = new List<string> { "apple", "banana", "cherry" };

// From array
int[] arr = { 1, 2, 3, 4, 5 };
var fromArr = new List<int>(arr);

// With initial capacity (avoids reallocations when count is known)
var scores = new List<double>(capacity: 1000);

S2.2 Adding and Removing

var list = new List<string> { "a", "b", "c" };

list.Add("d");              // ["a", "b", "c", "d"]
list.Insert(1, "x");        // ["a", "x", "b", "c", "d"]
list.AddRange(new[] { "e", "f" });

list.Remove("x");           // removes first "x"
list.RemoveAt(0);           // removes element at index 0
list.RemoveAll(s => s == "b");  // removes all matching

Console.WriteLine(list.Count);   // remaining count

S2.3 Accessing and Iterating

var nums = new List<int> { 10, 20, 30, 40, 50 };

Console.WriteLine(nums[0]);    // 10 - index access
Console.WriteLine(nums[^1]);   // 50 - index from end
Console.WriteLine(nums.Count); // 5

// Range slice (returns a new List)
var slice = nums[1..4];        // [20, 30, 40]

foreach (int n in nums)
    Console.Write($"{n} ");

// With index
for (int i = 0; i < nums.Count; i++)
    Console.WriteLine($"{i}: {nums[i]}");

S2.4 Searching and Sorting

var words = new List<string> { "cherry", "apple", "banana" };

bool has = words.Contains("apple");        // True
int idx = words.IndexOf("banana");         // 2
int last = words.LastIndexOf("apple");     // 0

words.Sort();              // in-place ascending
words.Reverse();           // in-place reverse

// Sort by custom key
words.Sort((a, b) => a.Length.CompareTo(b.Length));

// Find and filter
string? found = words.Find(w => w.StartsWith("a"));  // "apple"
List<string> longOnes = words.FindAll(w => w.Length > 5);

S2.5 Conversions

var list = new List<int> { 3, 1, 4, 1, 5, 9 };

int[] array  = list.ToArray();
var set      = new HashSet<int>(list);  // removes duplicates

// Projection
List<string> strings = list.ConvertAll(n => n.ToString());

// LINQ (covered in detail in the LINQ tutorial)
var distinct = list.Distinct().OrderBy(n => n).ToList();
Console.WriteLine(string.Join(", ", distinct));  // 1, 3, 4, 5, 9

S2.6 Example - All Together

// List - student grade tracker with sort and filter.

var students = new List<(string Name, int Score)>
{
    ("Alice", 92), ("Bob", 78), ("Carol", 95), ("Dave", 83), ("Eve", 78)
};

students.Sort((a, b) => b.Score.CompareTo(a.Score));  // descending

Console.WriteLine("Ranked:");
for (int i = 0; i < students.Count; i++)
    Console.WriteLine($"  {i + 1}. {students[i].Name,-8} {students[i].Score}");

var passing = students.FindAll(s => s.Score >= 80);
Console.WriteLine($"\nPassing: {passing.Count}");
Expected output:
Ranked:
  1. Carol    95
  2. Alice    92
  3. Dave     83
  4. Bob      78
  5. Eve      78

Passing: 3

S2.7 Exercise

Exercise
  • Create a List<int> of 20 random integers (1-100). Print the top 5 largest using Sort and Reverse.
  • Remove all duplicates from the list using Distinct(). Print before and after counts.
  • Use FindAll to get all values divisible by 3. Use ConvertAll to produce a List<string> of their string representations.

S2.8 Common Mistakes

Modifying a list while iterating with foreach

var list = new List<int> { 1, 2, 3, 4 };
foreach (var n in list)
    if (n % 2 == 0) list.Remove(n);  // InvalidOperationException
Use RemoveAll for conditional removal, or iterate a copy with list.ToList().

Using list.Count instead of list.Count - 1 as last index

var last = list[list.Count];    // ArgumentOutOfRangeException
var last = list[list.Count - 1]; // correct
var last = list[^1];             // preferred range syntax

S2.9 Key Terms

TermMeaning
List<T>Generic dynamic array; grows automatically as elements are added
CountNumber of elements currently in the list
CapacityCurrent allocated buffer size; doubles when exceeded
Add / AddRangeAppends one or many elements
Insert / RemoveAtAdds or removes at a specific index; O(n)
FindAllReturns a new list of elements matching a predicate
SortIn-place sort using natural order or a custom comparer
ConvertAllProjects each element through a function, returning a new list