Collections — List, Dictionary, Array

লেসন ৭ / ৫০

Array

// Fixed size
int[] nums = new int[5];           // [0,0,0,0,0]
int[] primes = { 2, 3, 5, 7, 11 };
string[] names = new string[] { "Rahim", "Karim" };

nums[0] = 10;
Console.WriteLine(nums.Length);

// Multi-dimensional
int[,] matrix = new int[3, 3];
matrix[0, 0] = 1;

int[][] jagged = new int[3][];     // jagged
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

List<T> ⭐ (Dynamic array)

using System.Collections.Generic;

var list = new List<int> { 1, 2, 3 };
list.Add(4);
list.AddRange(new[] { 5, 6 });
list.Remove(2);                    // value
list.RemoveAt(0);                  // index
list.Insert(0, 100);
bool exists = list.Contains(3);
int idx = list.IndexOf(5);
list.Sort();
list.Reverse();
Console.WriteLine(list.Count);

foreach (var n in list) Console.WriteLine(n);

Dictionary<TKey, TValue> ⭐

var dict = new Dictionary<string, int> {
    { "Rahim", 25 },
    { "Karim", 30 }
};

dict["Sumon"] = 28;                // add/update
dict.Add("Nadia", 22);             // throw if exists

if (dict.ContainsKey("Rahim")) {
    Console.WriteLine(dict["Rahim"]);
}

if (dict.TryGetValue("Karim", out int age)) {
    Console.WriteLine(age);
}

dict.Remove("Sumon");

foreach (var kvp in dict) {
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

HashSet<T> — Unique values

var set = new HashSet<int> { 1, 2, 3 };
set.Add(2);                         // false (duplicate)
set.Add(4);                         // true

bool has = set.Contains(3);
set.UnionWith(new[] { 5, 6 });
set.IntersectWith(new[] { 2, 5 });

Queue<T> — FIFO

var q = new Queue<string>();
q.Enqueue("First");
q.Enqueue("Second");
string first = q.Dequeue();         // "First"
string peek = q.Peek();             // দেখো না সরিয়ে

Stack<T> — LIFO

var s = new Stack<int>();
s.Push(1); s.Push(2); s.Push(3);
int top = s.Pop();                  // 3

LinkedList, SortedDictionary

var ll = new LinkedList<int>();
ll.AddFirst(1);
ll.AddLast(2);

var sd = new SortedDictionary<string, int>();   // auto-sort by key