Lesson 9 — Fixed Collections
Arrays
C# arrays are zero-indexed and fixed-size like Java's, with LINQ extension methods providing powerful one-line operations for sorting, filtering, and aggregating.
CSHARP — Declarations and ranges
int[] marks = { 65, 72, 80, 58, 91 };
string[] names = new string[4];
names[0] = "Thandi";
names[1] = "Sipho";
Console.WriteLine(marks[0]); // 65
Console.WriteLine(marks[^1]); // 91 — C# index from end
Console.WriteLine(marks.Length); // 5
// Slice with range (C# 8+):
int[] first3 = marks[0..3]; // { 65, 72, 80 }
int[] last2 = marks[^2..]; // { 58, 91 }
Console.WriteLine(string.Join(", ", first3));
LINQ on Arrays
LINQ extension methods (from System.Linq) provide one-line aggregation, filtering, and sorting on any array or collection.
CSHARP — LINQ aggregation
using System.Linq;
int[] marks = { 65, 72, 80, 58, 91 };
Console.WriteLine($"Max: {marks.Max()}");
Console.WriteLine($"Min: {marks.Min()}");
Console.WriteLine($"Average: {marks.Average():F1}");
Console.WriteLine($"Sum: {marks.Sum()}");
Console.WriteLine($"Count >=70: {marks.Count(m => m >= 70)}");
// Sort (returns new array, does not modify original):
var sorted = marks.OrderBy(m => m).ToArray();
Console.WriteLine(string.Join(", ", sorted)); // 58, 65, 72, 80, 91
// Array.Sort modifies in place:
Array.Sort(marks);
Console.WriteLine(string.Join(", ", marks));
2D Arrays
CSHARP — 2D arrays
int[,] grades = {
{ 75, 82, 68 }, // Learner 1
{ 60, 55, 72 }, // Learner 2
{ 90, 88, 95 } // Learner 3
};
// Access: [row, column] — both zero-based
Console.WriteLine(grades[1, 2]); // 72
// Iterate:
for (int row = 0; row < grades.GetLength(0); row++) {
for (int col = 0; col < grades.GetLength(1); col++)
Console.Write($"{grades[row, col],4}");
Console.WriteLine();
}
Practice Task
Your Turn
Create an int array of 8 marks. Use LINQ to find max, min, average, and count of passing marks (>= 50). Sort the array and print it. Create a second array of only the passing marks using LINQ's Where method.
Common Mistakes
- Last valid index is Length - 1.
- 2D arrays use comma syntax:
arr[row, col]notarr[row][col]. - Forgetting
using System.Linq;for LINQ methods. - Array.Sort modifies in place; LINQ OrderBy returns a new sequence.
Professional Tip
C# range syntax (arr[1..4]) and index-from-end (arr[^1]) are elegant — learn them for working with arrays and spans.
Mini Quiz
How do you access row 2, column 1 of a C# 2D array?
C# 2D arrays use comma-separated indexes inside single brackets, both zero-based.