Introduction
A dictionary stores pairs of keys and values so you can quickly find a value by its key.
Jump into concepts and practice - no test required
A dictionary stores pairs of keys and values so you can quickly find a value by its key.
Dictionary<TKey, TValue> dictionaryName = new Dictionary<TKey, TValue>();Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
int age = ages["Alice"];
bool hasBob = ages.ContainsKey("Bob");This program creates a phone book dictionary, adds three contacts, and prints their numbers. It also lists all contacts.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, string> phoneBook = new Dictionary<string, string>(); phoneBook.Add("John", "555-1234"); phoneBook.Add("Jane", "555-5678"); phoneBook["Bob"] = "555-8765"; // Another way to add Console.WriteLine("John's number: " + phoneBook["John"]); if (phoneBook.ContainsKey("Jane")) { Console.WriteLine("Jane's number: " + phoneBook["Jane"]); } Console.WriteLine("All contacts:"); foreach (var entry in phoneBook) { Console.WriteLine(entry.Key + ": " + entry.Value); } } }
Trying to get a value with a key that does not exist will cause an error. Use ContainsKey to check first.
You can update a value by assigning a new value to an existing key.
Dictionaries are very fast for lookups compared to lists.
Dictionaries store data as key-value pairs for quick access.
Keys must be unique and are used to find values.
Use Add() to insert and indexer [] to get or set values.
Dictionary in C#?Dictionary<int, string> named dict?Add(key, value).Add. dict[1] = "apple"; uses indexer which sets or updates but is not the method to add explicitly.var dict = new Dictionary<int, string>(); dict.Add(1, "one"); dict[2] = "two"; Console.WriteLine(dict[1] + ", " + dict[2]);
var dict = new Dictionary<int, string>(); dict.Add(1, "apple"); dict.Add(1, "banana");
var users = new List<(int id, string name)> { (1, "Alice"), (2, "Bob"), (3, "Charlie") };Dictionary<int, string> mapping IDs to names using a dictionary comprehension style?