C# Tutorial · Collections and LINQ · Lesson 16 of 22

C# Lists and Dictionaries

List<T>, Dictionary<TKey,TValue>, HashSet<T> and collection expressions.

List<T>

Example 1
List<string> todo = ["Plan", "Code"];   // collection expression (C# 12)
todo.Add("Test");
todo.Insert(0, "Coffee");
todo.Remove("Plan");
Console.WriteLine($"{string.Join(", ", todo)} (count {todo.Count})");
Console.WriteLine(todo.Contains("Code") + " " + todo.IndexOf("Test"));
var nums = new List<int> { 5, 3, 9, 1 };
nums.Sort();
nums.RemoveAll(n => n > 4);
Console.WriteLine(string.Join(",", nums));

Output

Coffee, Code, Test (count 3)
True 2
1,3

Run this on your computer — see “Get Started” for setup.

Dictionary and HashSet

Dictionary<TKey, TValue> maps keys to values; TryGetValue avoids exceptions for missing keys. HashSet<T> stores unique values:

Example 2
var stock = new Dictionary<string, int> { ["apples"] = 5, ["pears"] = 2 };
stock["plums"] = 12;
stock["apples"] += 3;
Console.WriteLine(stock["apples"]);
if (!stock.TryGetValue("kiwis", out int kiwis))
    Console.WriteLine("no kiwis");
foreach (var (fruit, qty) in stock.OrderBy(kv => kv.Key))
    Console.WriteLine($"{fruit}: {qty}");

var tags = new HashSet<string> { "csharp", "dotnet" };
Console.WriteLine(tags.Add("csharp") + " " + tags.Count);

Output

8
no kiwis
apples: 8
pears: 2
plums: 12
False 2

Run this on your computer — see “Get Started” for setup.

Test yourself

Which Dictionary method reads a value without throwing if the key is missing?

  1. Get
  2. TryGetValue
  3. Find
  4. ContainsValue
Show answer

Answer: TryGetValue

Practice next