C# Dictionary
A Dictionary is a collection that pairs each key with one value. A key is looked up to read its value.
Add and Read Pairs
The indexer adds two pairs of name and age. One age prints, then the pair count.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Hana"] = 27;
ages["Bo"] = 31;
Console.WriteLine(ages["Hana"]);
Console.WriteLine(ages.Count);
}
}Update and Check Keys
Assigning to the key Hana replaces the old age. ContainsKey answers for a present key and a missing key.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Hana"] = 27;
ages["Bo"] = 31;
ages["Hana"] = 28;
Console.WriteLine(ages["Hana"]);
Console.WriteLine(ages.ContainsKey("Bo"));
Console.WriteLine(ages.ContainsKey("Mina"));
}
}List Pairs in Order
The keys are copied into a list and sorted first. The loop then prints each pair in key order.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Hana"] = 27;
ages["Bo"] = 31;
List<string> keys = new List<string>(ages.Keys);
keys.Sort();
foreach (string key in keys)
{
Console.WriteLine(key + ": " + ages[key]);
}
}
}Example
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> stock = new Dictionary<string, int>();
stock["Pens"] = 8;
stock["Pencils"] = 12;
stock["Rulers"] = 5;
List<string> keys = new List<string>(stock.Keys);
keys.Sort();
foreach (string key in keys)
{
Console.WriteLine(key + ": " + stock[key]);
}
Console.WriteLine("Kinds: " + stock.Count);
}
}Key points
- Dictionary<K, V>: a collection that pairs keys with values.
- The first type in the brackets is the key type.
- The second type in the brackets is the value type.
- Write a pair by assigning to the key in square brackets.
- Read a value by writing its key in square brackets.
- Count: a property that holds how many pairs the dictionary holds.
- ContainsKey reports whether a key is present.
In this example, the dictionary holds a stock count for each item name. The keys are copied into a list and sorted. The loop prints Pencils with 12, then Pens with 8, then Rulers with 5. The last line prints the Count of pairs, which is 3.
Note
A key can appear only once. Assigning to it again updates the pair instead of adding one.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
What does ages["Hana"] = 28 do when the key "Hana" already holds 27?