Roadmap › C# Language — Basics to Advanced › Module: Arrays and Collections
Lessons in this course (38)

11. List<T> and Dictionary<TKey, TValue> in depth

Basic★ Must knowLesson 11 of 38
csharp
var names = new List<string> { "Ravi", "Asha" };
names.Add("Meera");
names.AddRange(["Kiran", "John"]);
names.Insert(0, "Zoya");                  // at index
names.Remove("John");                     // first match; returns bool
names.RemoveAt(0);
names.RemoveAll(n => n.StartsWith("K"));
bool hasAsha = names.Contains("Asha");
int idx = names.IndexOf("Meera");
string? first = names.Find(n => n.Length > 4);
names.Sort();                             // in place
names.ForEach(Console.WriteLine);
Console.WriteLine($"{names.Count} items, capacity {names.Capacity}");
  • List<T> is a resizable array: Count = items, Capacity = allocated slots; when full it doubles and copies — pass an initial capacity if you know the size.
  • Index access O(1); Contains/IndexOf/Remove are O(n); inserting at the start is O(n).
csharp
var stock = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
    ["pen"] = 10,
    ["book"] = 4
};
stock.Add("bag", 2);                      // throws ArgumentException if the key exists
stock["pen"] = 12;                        // add or overwrite
if (stock.TryGetValue("book", out int qty)) Console.WriteLine(qty);
stock.TryAdd("pen", 99);                  // false — key already there, no exception
bool removed = stock.Remove("bag");
foreach (var (item, count) in stock) Console.WriteLine($"{item}: {count}");
// var x = stock["laptop"];               // KeyNotFoundException — use TryGetValue
  • Average O(1) lookup using the key's GetHashCode() and Equals(); keys must be unique and not null.
  • Iteration order is not guaranteed — use SortedDictionary/SortedList or sort with LINQ when order matters.
  • Custom key types must override Equals and GetHashCode consistently (records do this for you).