Array: Fixed Size. List: Flexible
// Array - size = 3, cannot change
string[] cart = new string[3];
cart[0] = "Laptop";
// List - add/remove anytime
List<string> cart2 = new();
cart2.Add("Laptop");
cart2.Add("Mouse");
cart2.Remove("Mouse");
Rule: Use List<T> 99% of the time.
Arrays: When Size is Known
int[] scores = new int[5]; // 5 slots, all 0
int[] scores2 = { 90, 85, 95, 88, 92 }; // Initialize with values
Console.WriteLine(scores2[0]); // 90. Index starts at 0
Console.WriteLine(scores2.Length); // 5
Multi-Dimensional Arrays
int[,] matrix = new int[3, 3]; // 3x3 grid
matrix[0, 0] = 1;
matrix[2, 2] = 9;
// Tic-tac-toe board
char[,] board = {
{ 'X', 'O', 'X' },
{ 'O', 'X', 'O' },
{ 'X', 'O', 'X' }
};
List<T>: The Real MVP
List<int> numbers = new();
numbers.Add(10);
numbers.AddRange(new[] { 20, 30 });
numbers.Insert(1, 15); // Insert 15 at index 1
numbers.Remove(20); // Remove first 20
numbers.RemoveAt(0); // Remove at index 0
bool has30 = numbers.Contains(30); // true
int idx = numbers.IndexOf(30); // 1
LINQ: Query Lists Like SQL
List<int> nums = new() { 1, 5, 3, 9, 2, 8 };
var even = nums.Where(n => n % 2 == 0); // 2, 8
var sorted = nums.OrderBy(n => n); // 1,2,3,5,8,9
var sum = nums.Sum(); // 28
var max = nums.Max(); // 9
Array vs List Performance
| Array | List<T> |
| Access by index | O(1) - instant | O(1) - instant |
| Add/Remove | Impossible | O(n) - slow if big |
| Memory | Less overhead | Extra capacity |
Quick Check ๐ง
Easy Q1: Can you add a 4th item to string[3]?
Medium Q1: What is index of first element in C# array?
Hard Q2: LINQ: What does this return?
new[]{1,2,3,4}.Where(x => x > 5).Count()
No comments yet. Be the first to share your thoughts!