Arrays & Lists in C#
In real-world applications, you rarely work with single variables. You work with collections of data—lists of users, arrays of prices, or grids of pixels. C# provides powerful tools to manage these collections efficiently.
1. Arrays: Fixed-Size Collections
An array is a contiguous block of memory that holds a fixed number of elements of the same type.
Types of Arrays
- Single-Dimensional: A simple row of data.
int[] numbers = new int[5] { 1, 2, 3, 4, 5 }; - Multi-Dimensional (Rectangular): A grid with fixed rows and columns.
int[,] matrix = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } }; Console.WriteLine(matrix[0, 1]); // Output: 2 - Jagged Arrays: An "array of arrays" where each sub-array can have a different length.
int[][] jagged = new int[3][]; jagged[0] = new int[] { 1, 2 }; jagged[1] = new int[] { 3, 4, 5, 6 }; jagged[2] = new int[] { 7 };
Practical Example: Matrix Operations
Multi-dimensional arrays are perfect for mathematical matrix operations.
1. Matrix Addition
To add two matrices, they must have the same dimensions. You simply add the corresponding elements.
int[,] matrixA = { { 1, 2 }, { 3, 4 } };
int[,] matrixB = { { 5, 6 }, { 7, 8 } };
int[,] result = new int[2, 2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i, j] = matrixA[i, j] + matrixB[i, j];
}
}
// Result: { { 6, 8 }, { 10, 12 } }
2. Matrix Multiplication
Multiplication is more complex: the value at result[i, j] is the sum of the products of the i-th row of A and the j-th column of B.
int[,] A = { { 1, 2 }, { 3, 4 } };
int[,] B = { { 5, 6 }, { 7, 8 } };
int[,] C = new int[2, 2];
for (int i = 0; i < 2; i++) { // Rows of A
for (int j = 0; j < 2; j++) { // Columns of B
C[i, j] = 0;
for (int k = 0; k < 2; k++) { // Shared dimension
C[i, j] += A[i, k] * B[k, j];
}
}
}
// Result: { { 19, 22 }, { 43, 50 } }
Important Array Class Methods
The System.Array class provides static methods to manipulate arrays.
Array.Sort(): Sorts elements in ascending order.Array.Reverse(): Reverses the order of elements.Array.IndexOf(): Returns the index of the first occurrence of a value.Array.Clear(): Sets a range of elements to their default value (e.g.,0forint).Array.Copy(): Copies a range of elements from one array to another.
int[] scores = { 45, 12, 98, 33, 75 };
Array.Sort(scores); // { 12, 33, 45, 75, 98 }
Array.Reverse(scores); // { 98, 75, 45, 33, 12 }
int index = Array.IndexOf(scores, 45); // 2
2. List: Dynamic Collections
List<T> is part of System.Collections.Generic. Unlike arrays, lists can grow and shrink dynamically as you add or remove items.
Common List Operations
List<string> tasks = new List<string> { "Coding", "Testing" };
tasks.Add("Deploying"); // Add to end
tasks.Insert(1, "Reviewing"); // Insert at specific index
tasks.AddRange(new[] { "Doc", "Fix" }); // Add multiple
tasks.Remove("Testing"); // Remove by value
tasks.RemoveAt(0); // Remove by index
bool hasFix = tasks.Contains("Fix"); // Check existence
int count = tasks.Count; // Get current size
When to use List vs Array?
- Use Array: When the size is fixed and known at compile time (e.g., days of the week) or for high-performance memory-critical applications.
- Use List: In 95% of standard application development where data size changes at runtime.
3. LINQ & Extension Methods
LINQ (Language Integrated Query) allows you to perform powerful queries on arrays and lists using extension methods found in the System.Linq namespace.
Common LINQ Methods
| Method | Description |
|---|---|
Where | Filters elements based on a condition. |
Select | Transforms each element into a new form. |
OrderBy / OrderByDescending | Sorts the collection. |
First / FirstOrDefault | Gets the first element (or a default if empty). |
Any | Returns true if at least one element matches a condition. |
All | Returns true if ALL elements match a condition. |
Sum, Average, Max, Min | Numerical aggregations. |
Practical Examples
using System.Linq;
int[] numbers = { 5, 10, 15, 20, 25, 30 };
// 1. Filter: Numbers greater than 15
var largeNumbers = numbers.Where(n => n > 15).ToArray();
// 2. Transform: Convert numbers to strings with a prefix
var labels = numbers.Select(n => $"Value: {n}").ToList();
// 3. Aggregation
int total = numbers.Sum();
double avg = numbers.Average();
// 4. Quick Checks
bool hasEvens = numbers.Any(n => n % 2 == 0); // true
bool allPositive = numbers.All(n => n > 0); // true
// 5. Finding specific items
int firstLarge = numbers.First(n => n > 20); // 25
4. Iterating Collections
The foreach Loop
The cleanest way to read every item. It works for both arrays and lists.
foreach (var number in numbers)
{
Console.WriteLine(number);
}
The for Loop
Use this if you need the index of the item during iteration.
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Index {i} has value {numbers[i]}");
}