Skip to content
C#

Collections

Use List, Dictionary, HashSet, Queue, Stack, and read-only views.

By EZ4Code Team
collectionslistdictionary

Code

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// List - ordered, indexable
var list = new List<int> { 3, 1, 2 };
list.Add(4);
list.Sort();
Console.WriteLine(string.Join(",", list));     // 1,2,3,4

// Dictionary - key/value
var dict = new Dictionary<string, int>();
dict["a"] = 1;
dict.TryGetValue("b", out int v);
Console.WriteLine($"has b? {dict.ContainsKey("b")}");

// HashSet - unique elements
var set = new HashSet<int> { 1, 2, 2, 3 };
set.Add(2);
Console.WriteLine($"set count = {set.Count}");  // 3

// Queue and Stack
var q = new Queue<string>();
q.Enqueue("a"); q.Enqueue("b");
Console.WriteLine(q.Dequeue());

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

// Read-only wrapper
var ro = new ReadOnlyCollection<int>(list);
Console.WriteLine(ro[0]);

Explanation

List<T> is a growable array, Dictionary<TKey,TValue> maps keys to values, and HashSet<T> enforces uniqueness with O(1) lookups. Queue<T> and Stack<T> provide FIFO and LIFO semantics respectively. ReadOnlyCollection<T> wraps a list so external callers can read but not mutate it.

More C# Snippets