8. Arrays and Collections

An array stores a fixed number of items of the same type in one variable. Its size is set when it is created and cannot change, indexes start at 0, and the last valid index is Length - 1 (reading outside throws IndexOutOfRangeException). Arrays are reference types: copying the variable copies the reference, not the items. There are three kinds: the single-dimensional (normal) array int[], the multidimensional rectangular array such as the 2D matrix int[,] (every row has the same length), and the jagged array int[][] (an array of arrays, where each row can have a different length).

The static Array class provides Sort, Reverse, IndexOf, BinarySearch, Copy, Resize, Clear, Fill and Exists. Arrays also support index-from-end (a[^1]) and ranges (a[1..3]). When the size must change, use a collection from System.Collections.Generic: List<T> is a resizable list, Dictionary<K,V> stores key/value pairs with very fast lookup by key, HashSet<T> stores unique values and offers set maths (union, intersection), Queue<T> is first-in-first-out, Stack<T> is last-in-first-out, LinkedList<T> is a linked chain, and SortedDictionary / SortedSet keep their items in order.

Pick the simplest structure that fits: an array for a fixed number of items or a matrix, List<T> for a changing sequence, Dictionary when you look things up by a key, HashSet when duplicates must be avoided, Queue for waiting lines and Stack for undo or backtracking. All of them can be walked with foreach and queried with LINQ.

Key points to remember

  • Array: use Length (a property). List<T>, Dictionary, HashSet: use Count. For a 2D array, Length is the total number of items; use GetLength(0) for rows and GetLength(1) for columns.
  • Create arrays with new int[5] (all zeros), with values { 1, 2, 3 }, or new[] { 1, 2, 3 } (type inferred). Strings default to null, numbers to 0, bool to false.
  • Rectangular int[,] is one block of memory and suits grids and matrices. Jagged int[][] needs each row to be created separately but allows rows of different sizes (Pascal's triangle, lists of lists).
  • Common mistake: array[array.Length] is one past the end. The last item is array[array.Length - 1] or array[^1].
  • Common mistake: int[] b = a; does not copy. Use a.Clone(), Array.Copy or a.ToArray() to get an independent copy.
  • List<T> grows automatically. Add, AddRange, Insert, Remove, RemoveAt, RemoveAll, Contains, IndexOf, Find, FindAll, Sort, Reverse, Clear and ToArray are the methods you use most.
  • Dictionary keys must be unique: Add throws if the key exists, indexer assignment (d[key] = v) adds or replaces, and reading a missing key with d[key] throws KeyNotFoundException. Use TryGetValue or ContainsKey to be safe.
  • Never add or remove items in a collection while a foreach is walking it. Loop backwards with for, use RemoveAll, or iterate over a copy.
  • List<List<int>> is the resizable equivalent of a jagged array; List<T> and Dictionary<K,V> are generic, so they are type-safe and need no casting (the old ArrayList and Hashtable should not be used).
  • Arrays and List<T> are not thread-safe. For several threads use the collections in System.Collections.Concurrent.

Example 1: Single-dimensional arrays

C#
int[] a = new int[3];            // {0, 0, 0}
a[0] = 10; a[1] = 20; a[2] = 30;

int[] b = { 4, 8, 15, 16 };      // with values
string[] names = new string[] { "Ann", "Ben" };
var c = new[] { 1.5, 2.5 };      // inferred double[]
bool[] flags = new bool[2];

Console.WriteLine(a.Length);
Console.WriteLine(b[0] + " " + b[b.Length - 1]);
Console.WriteLine(b[^1]);                    // last item
Console.WriteLine(names[1]);
Console.WriteLine(string.Join(",", new int[5]));
Console.WriteLine(flags[0]);
Console.WriteLine(c.GetType());
Show output Output
3
4 16
16
Ben
0,0,0,0,0
False
System.Double[]

Example 2: Looping and aggregating an array

C#
int[] scores = { 70, 85, 90, 65 };

int total = 0;
for (int i = 0; i < scores.Length; i++)
    total += scores[i];

Console.WriteLine(total);
Console.WriteLine((double)total / scores.Length);
Console.WriteLine(scores.Max() + " " + scores.Min());

foreach (int s in scores)
    if (s >= 80) Console.Write(s + " ");
Console.WriteLine();

for (int i = scores.Length - 1; i >= 0; i--)    // backwards
    Console.Write(scores[i] + " ");
Show output Output
310
77.5
90 65
85 90
65 90 85 70

Example 3: Changing array items

C#
double[] prices = { 10.0, 20.0, 30.0 };

for (int i = 0; i < prices.Length; i++)
    prices[i] *= 1.10;                    // +10 percent, changing the array

Console.WriteLine(string.Join(", ", prices.Select(p => p.ToString("F2"))));

string[] words = { "red", "green" };
for (int i = 0; i < words.Length; i++)
    words[i] = words[i].ToUpper();
Console.WriteLine(string.Join(" ", words));
Show output Output
11.00, 22.00, 33.00
RED GREEN

Example 4: The Array class: sort, search, copy, resize

C#
int[] nums = { 5, 3, 9, 1 };

Array.Sort(nums);
Console.WriteLine(string.Join(",", nums));
Console.WriteLine(Array.BinarySearch(nums, 5));       // sorted arrays only
Array.Reverse(nums);
Console.WriteLine(string.Join(",", nums));
Console.WriteLine(Array.IndexOf(nums, 3));
Console.WriteLine(Array.Exists(nums, n => n > 8));

int[] copy = new int[4];
Array.Copy(nums, copy, 4);
Array.Clear(copy, 0, 2);                              // zero the first two
Console.WriteLine(string.Join(",", copy));

Array.Resize(ref nums, 6);                            // new, longer array
Console.WriteLine(string.Join(",", nums));

int[] filled = new int[3];
Array.Fill(filled, 7);
Console.WriteLine(string.Join(",", filled));
Show output Output
1,3,5,9
2
9,5,3,1
2
True
0,0,3,1
9,5,3,1,0,0
7,7,7

Example 5: Index and range operators

C#
int[] n = { 10, 20, 30, 40, 50 };

Console.WriteLine(n[^1]);                        // last
Console.WriteLine(n[^2]);                        // second from last
Console.WriteLine(string.Join(",", n[1..3]));    // index 1 up to (not including) 3
Console.WriteLine(string.Join(",", n[..2]));
Console.WriteLine(string.Join(",", n[^2..]));
Console.WriteLine(string.Join(",", n[..]));      // a copy of everything
Show output Output
50
40
20,30
10,20
40,50
10,20,30,40,50

Example 6: Arrays are reference types

C#
int[] a = { 1, 2, 3 };
int[] b = a;                         // same array, two names
b[0] = 99;
Console.WriteLine(a[0]);

int[] c = (int[])a.Clone();          // independent copy
c[1] = 50;
Console.WriteLine(a[1]);

try
{
    Console.WriteLine(a[5]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Index out of range");
}
Show output Output
99
2
Index out of range

Example 7: 2D arrays (matrices)

C#
int[,] matrix = new int[2, 3]
{
    { 1, 2, 3 },
    { 4, 5, 6 }
};

Console.WriteLine(matrix[1, 2]);            // row 1, column 2
Console.WriteLine(matrix.GetLength(0));     // rows
Console.WriteLine(matrix.GetLength(1));     // columns
Console.WriteLine(matrix.Length);           // total items
Console.WriteLine(matrix.Rank);             // number of dimensions

for (int r = 0; r < matrix.GetLength(0); r++)
{
    for (int c = 0; c < matrix.GetLength(1); c++)
        Console.Write(matrix[r, c] + " ");
    Console.WriteLine();
}

matrix[0, 0] = 100;
foreach (int value in matrix)               // foreach visits every item
    Console.Write(value + " ");
Show output Output
6
2
3
6
2
1 2 3
4 5 6
100 2 3 4 5 6

Example 8: Matrix calculations: row sums, diagonal, transpose

C#
int[,] m =
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};
int size = m.GetLength(0);

for (int r = 0; r < size; r++)
{
    int rowSum = 0;
    for (int c = 0; c < size; c++) rowSum += m[r, c];
    Console.WriteLine($"Row {r} sum = {rowSum}");
}

int diagonal = 0;
for (int i = 0; i < size; i++) diagonal += m[i, i];
Console.WriteLine("Diagonal = " + diagonal);

int[,] t = new int[size, size];              // transpose: swap rows and columns
for (int r = 0; r < size; r++)
    for (int c = 0; c < size; c++)
        t[c, r] = m[r, c];

for (int r = 0; r < size; r++)
    Console.WriteLine($"{t[r, 0]} {t[r, 1]} {t[r, 2]}");
Show output Output
Row 0 sum = 6
Row 1 sum = 15
Row 2 sum = 24
Diagonal = 15
1 4 7
2 5 8
3 6 9

Example 9: Adding two matrices

C#
int[,] a = { { 1, 2 }, { 3, 4 } };
int[,] b = { { 10, 20 }, { 30, 40 } };
int[,] sum = new int[2, 2];

for (int r = 0; r < 2; r++)
    for (int c = 0; c < 2; c++)
        sum[r, c] = a[r, c] + b[r, c];

for (int r = 0; r < 2; r++)
    Console.WriteLine(sum[r, 0] + " " + sum[r, 1]);
Show output Output
11 22
33 44

Example 10: 3D arrays

C#
int[,,] cube = new int[2, 3, 4];     // 2 layers, 3 rows, 4 columns
cube[1, 2, 3] = 7;

Console.WriteLine(cube.Rank);
Console.WriteLine(cube.Length);
Console.WriteLine(cube.GetLength(2));
Console.WriteLine(cube[1, 2, 3]);
Show output Output
3
24
4
7

Example 11: Jagged arrays (arrays of arrays)

C#
int[][] jagged = new int[3][];       // 3 rows, columns not created yet
jagged[0] = new int[] { 1 };
jagged[1] = new int[] { 2, 3 };
jagged[2] = new int[] { 4, 5, 6 };

Console.WriteLine(jagged[2][1]);     // row 2, item 1
Console.WriteLine(jagged.Length);    // number of rows
Console.WriteLine(jagged[1].Length); // length of one row

for (int i = 0; i < jagged.Length; i++)
    Console.WriteLine(string.Join(" ", jagged[i]));

int[][] quick = { new[] { 1, 2 }, new[] { 3 } };      // shorthand
foreach (int[] row in quick)
    foreach (int value in row)
        Console.Write(value + " ");
Show output Output
5
3
2
1
2 3
4 5 6
1 2 3

Example 12: Jagged array: Pascal's triangle

C#
int[][] tri = new int[5][];

for (int i = 0; i < tri.Length; i++)
{
    tri[i] = new int[i + 1];              // row i has i + 1 items
    tri[i][0] = tri[i][i] = 1;            // both ends are 1
    for (int j = 1; j < i; j++)
        tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j];
    Console.WriteLine(string.Join(" ", tri[i]));
}
Show output Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Example 13: List<T>: add, insert, remove, search, sort

C#
var list = new List<string> { "a", "b" };
list.Add("c");
list.AddRange(new[] { "d", "e" });
list.Insert(1, "x");             // a x b c d e
list.Remove("a");                // x b c d e
list.RemoveAt(0);                // b c d e

Console.WriteLine(list.Count);
Console.WriteLine(list.Contains("c"));
Console.WriteLine(list.IndexOf("d"));

list[0] = "B";                   // B c d e
list.Reverse();                  // e d c B
list.Sort();                     // B c d e
Console.WriteLine(string.Join(",", list));

list.Clear();
Console.WriteLine(list.Count);
Show output Output
4
True
2
B,c,d,e
0

Example 14: List<T> with predicates and conversion

C#
var nums = new List<int> { 5, 12, 8, 3, 20 };

Console.WriteLine(nums.Find(n => n > 10));                      // first match
Console.WriteLine(string.Join(",", nums.FindAll(n => n > 7)));  // all matches
Console.WriteLine(nums.Exists(n => n == 3));

nums.RemoveAll(n => n < 6);                                     // removes 5 and 3
nums.Sort((a, b) => b.CompareTo(a));                            // descending
Console.WriteLine(string.Join(",", nums));

int[] array = nums.ToArray();                                   // List to array
List<int> back = array.ToList();                                // array to List
Console.WriteLine(array.Length + " " + back.Count);
Show output Output
12
12,8,20
True
20,12,8
3 3

Example 15: List of objects

C#
var people = new List<Person> { new("Ann", 30), new("Ben", 25) };
people.Add(new Person("Cy", 41));

people.Sort((a, b) => a.Age.CompareTo(b.Age));      // youngest first
foreach (var p in people)
    Console.WriteLine($"{p.Name} {p.Age}");

Person? oldest = people.MaxBy(p => p.Age);
Console.WriteLine(oldest?.Name);

record Person(string Name, int Age);
Show output Output
Ben 25
Ann 30
Cy 41
Cy

Example 16: List of lists (a resizable table)

C#
var grid = new List<List<int>>();
grid.Add(new List<int> { 1, 2 });
grid.Add(new List<int> { 3 });
grid[0].Add(9);                       // rows can grow
grid[1].AddRange(new[] { 4, 5 });

Console.WriteLine(grid[0].Count);
Console.WriteLine(grid[1][2]);
foreach (var row in grid)
    Console.WriteLine(string.Join(" ", row));
Show output Output
3
5
1 2 9
3 4 5

Example 17: Dictionary

C#
var ages = new Dictionary<string, int>
{
    ["Ann"] = 30,
    ["Ben"] = 25
};
ages["Cy"] = 41;
if (ages.TryGetValue("Ben", out int a))
    Console.WriteLine(a);
foreach (var kv in ages)
    Console.WriteLine($"{kv.Key}: {kv.Value}");
Show output Output
25
Ann: 30
Ben: 25
Cy: 41

Example 18: Dictionary: add, update, remove, safe lookup

C#
var stock = new Dictionary<string, int>();
stock.Add("apple", 10);
stock["pear"] = 4;                       // add or replace
stock["apple"] += 5;                     // update

Console.WriteLine(stock["apple"]);
Console.WriteLine(stock.ContainsKey("kiwi"));
Console.WriteLine(stock.TryAdd("pear", 99));    // false: key already exists
stock.Remove("pear");
Console.WriteLine(stock.Count);
Console.WriteLine(string.Join(",", stock.Keys));
Console.WriteLine(string.Join(",", stock.Values));

try
{
    Console.WriteLine(stock["kiwi"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("No such key");
}
Show output Output
15
False
False
1
apple
15
No such key

Example 19: Dictionary: counting words

C#
string text = "to be or not to be";
var counts = new Dictionary<string, int>();

foreach (string word in text.Split(' '))
    counts[word] = counts.GetValueOrDefault(word) + 1;

foreach (var pair in counts)
    Console.WriteLine($"{pair.Key}: {pair.Value}");
Show output Output
to: 2
be: 2
or: 1
not: 1

Example 20: HashSet<T>: unique values and set operations

C#
var set = new HashSet<int> { 1, 2, 3 };
Console.WriteLine(set.Add(3));           // false: already there
Console.WriteLine(set.Add(4));           // true
Console.WriteLine(set.Count);

var other = new HashSet<int> { 3, 4, 5 };
var union = new HashSet<int>(set);
union.UnionWith(other);
Console.WriteLine(string.Join(",", union.OrderBy(x => x)));

set.IntersectWith(other);
Console.WriteLine(string.Join(",", set.OrderBy(x => x)));

var unique = new HashSet<int>(new[] { 1, 1, 2, 2, 3 });   // removes duplicates
Console.WriteLine(unique.Count);
Console.WriteLine(unique.Contains(2));
Show output Output
False
True
4
1,2,3,4,5
3,4
3
True

Example 21: Queue<T> and Stack<T>

C#
var queue = new Queue<string>();           // first in, first out
queue.Enqueue("A");
queue.Enqueue("B");
queue.Enqueue("C");
Console.WriteLine(queue.Dequeue());
Console.WriteLine(queue.Peek());
Console.WriteLine(queue.Count);

var stack = new Stack<int>();              // last in, first out
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine(stack.Pop());
Console.WriteLine(stack.Peek());
Console.WriteLine(stack.Count);
Show output Output
A
B
2
3
2
2

Example 22: Stack example: checking brackets

C#
static bool IsBalanced(string text)
{
    var stack = new Stack<char>();
    foreach (char ch in text)
    {
        if (ch == '(' || ch == '[') stack.Push(ch);
        else if (ch == ')' || ch == ']')
        {
            if (stack.Count == 0) return false;
            char open = stack.Pop();
            if ((ch == ')' && open != '(') || (ch == ']' && open != '[')) return false;
        }
    }
    return stack.Count == 0;
}

Console.WriteLine(IsBalanced("(a[b])"));
Console.WriteLine(IsBalanced("(a[b)]"));
Show output Output
True
False

Example 23: Sorted collections and LinkedList

C#
var sorted = new SortedDictionary<string, int>
{
    ["pear"] = 3, ["apple"] = 5, ["fig"] = 1
};
foreach (var kv in sorted)                  // always in key order
    Console.WriteLine($"{kv.Key}={kv.Value}");

var sortedSet = new SortedSet<int> { 5, 1, 3, 3 };
Console.WriteLine(string.Join(",", sortedSet));

var chain = new LinkedList<int>();
chain.AddLast(2);
chain.AddLast(3);
chain.AddFirst(1);
Console.WriteLine(string.Join("->", chain));
Show output Output
apple=5
fig=1
pear=3
1,3,5
1->2->3

Example 24: Collection initialisers and searching with LINQ

C#
var cities = new List<string> { "Cape Town", "Durban", "Johannesburg", "Pretoria" };

Console.WriteLine(cities.Contains("Durban"));
Console.WriteLine(cities.Count(c => c.Length > 7));
Console.WriteLine(cities.FirstOrDefault(c => c.StartsWith("P")));
Console.WriteLine(string.Join(", ", cities.OrderByDescending(c => c.Length).Take(2)));

var capitals = new Dictionary<string, string>
{
    { "South Africa", "Pretoria" },
    { "Kenya", "Nairobi" }
};
Console.WriteLine(capitals["Kenya"]);
Show output Output
True
3
Pretoria
Johannesburg, Cape Town
Nairobi