Summary - Collections
Combine List<T> and Dictionary<K,V> to write a phone book.
Summary - Collections
In this section you learned the List<T>, Dictionary<K,V> and HashSet<T> collections. They share the Add and Count members; they differ in item management. List is ordered, dictionary is keyed, set is unique.
Now we will combine them into a small phone book. We will use List for names, Dictionary for numbers and TryGetValue for safe lookup.
Exercise Add two people to the phone book
Declare Dictionary<string, string> phone = new Dictionary<string, string>();. Use Add to put "555-1000" under the key "Ayşe" and "555-2000" under "Mehmet". Then print phone.Count with Console.WriteLine.
Show example solution
Call phone.Add("Ayşe", "555-1000"); and phone.Add("Mehmet", "555-2000");, then print with Console.WriteLine(phone.Count);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare phone dictionary, add two people and print the count
Dictionary<string, string> phone = new Dictionary<string, string>();
phone.Add("Ayşe", "555-1000");
phone.Add("Mehmet", "555-2000");
Console.WriteLine(phone.Count);
}
}
Exercise Hold names with a list
Declare List<string> names = new List<string>();. Add the values "Ayşe" and "Mehmet" with Add. Then print names.Count with Console.WriteLine.
Show example solution
Declare with List<string> names = new List<string>();, call names.Add("..."); twice, then print with Console.WriteLine(names.Count);.
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare names list, add two names and print the count
List<string> names = new List<string>();
names.Add("Ayşe");
names.Add("Mehmet");
Console.WriteLine(names.Count);
}
}
Test yourself
-
What does phone.Count print after one Add?
Dictionary<string, string> phone = new Dictionary<string, string>(); phone.Add("Ayşe", "555-1000"); Console.WriteLine(phone.Count);- 0
- 1
- 2
- 555-1000
Show answer
1 — Correct. One pair was added; Count returns 1.
-
TryGetValue call
Dictionary<string, string> phone = new Dictionary<string, string>(); phone.Add("Ayşe", "555-1000"); string num; bool ok = ____; Console.WriteLine(ok);Show answer
Dictionary<string, string> phone = new Dictionary<string, string>(); phone.Add("Ayşe", "555-1000"); string num; bool ok = phone.TryGetValue("Ayşe", out num); Console.WriteLine(ok); -
Match the collections
- List<T>
- Ordered, dynamic
- Dictionary<K,V>
- Key-value
- HashSet<T>
- Unique
- TryGetValue
- Safe access