Generic Collections: List, Dictionary, Queue, Stack

Storing and working with groups of data

Posted by Rodrigo Castro on November 22, 2024

C# gives you powerful built-in collections to store groups of data.

📋 List

A resizable list of items.

1
2
3
4
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Console.WriteLine(names[0]); // Alice

📖 Dictionary<TKey, TValue>

Pairs of keys and values.

1
2
3
4
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
Console.WriteLine(ages["Bob"]); // 25

📦 Queue

First-in, first-out (FIFO).

1
2
3
4
Queue<string> queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
Console.WriteLine(queue.Dequeue()); // first

🗄️ Stack

Last-in, first-out (LIFO).

1
2
3
4
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
Console.WriteLine(stack.Pop()); // 2

💡 When to Use Each?

  • List: Simple list of items, access by index.
  • Dictionary: Lookup by key.
  • Queue: Process items in the order added.
  • Stack: Process items in reverse order.

Next: Declaring and using generic methods and classes!