๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Dictionary in Depth

Dictionary in depth covers lookups that stay safe when a key is missing. TryGetValue reports success or failure instead of throwing an exception.

Find a Value with TryGetValue

TryGetValue finds the key Hana. It returns true and the out argument holds the stored score.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> scores = new Dictionary<string, int>();
        scores["Hana"] = 88;
        scores["Bo"] = 74;
        int value;
        bool found = scores.TryGetValue("Hana", out value);
        Console.WriteLine(found);
        Console.WriteLine(value);
    }
}

A Missing Key Without an Exception

The key Mina is not in the dictionary. The else branch prints a plain line and the program keeps running.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> scores = new Dictionary<string, int>();
        scores["Hana"] = 88;
        scores["Bo"] = 74;
        int value;
        bool found = scores.TryGetValue("Mina", out value);
        if (found)
        {
            Console.WriteLine(value);
        }
        else
        {
            Console.WriteLine("Mina not found.");
        }
    }
}

Count Words into a Dictionary

Each word adds one to its total in the dictionary. The keys are copied to a list and sorted before printing.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string[] words = { "cat", "dog", "cat", "bird", "dog", "cat" };
        Dictionary<string, int> counts = new Dictionary<string, int>();
        foreach (string word in words)
        {
            if (counts.ContainsKey(word))
            {
                counts[word] = counts[word] + 1;
            }
            else
            {
                counts[word] = 1;
            }
        }
        List<string> keys = new List<string>(counts.Keys);
        keys.Sort();
        foreach (string key in keys)
        {
            Console.WriteLine(key + ": " + counts[key]);
        }
    }
}

Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> scores = new Dictionary<string, int>();
        scores["Hana"] = 88;
        scores["Bo"] = 74;
        scores["Mina"] = 91;
        Console.WriteLine(scores.Remove("Bo"));
        Console.WriteLine(scores.Count);
        List<string> keys = new List<string>(scores.Keys);
        keys.Sort();
        foreach (string key in keys)
        {
            Console.WriteLine(key + ": " + scores[key]);
        }
    }
}

Key points

  • TryGetValue tries a lookup and reports the result with its return value.
  • The out argument receives the stored value when the key is present.
  • A missing key makes TryGetValue return false.
  • No exception is thrown for a missing key.
  • Counting with a dictionary stores one running total for each key.
  • Remove deletes a pair and returns true when a pair was removed.

In this example, the dictionary holds three scores. Remove deletes the pair for Bo and returns True. The Count then reads 2. The keys are copied into a list and sorted. The loop prints Hana with 88 and then Mina with 91.

Note

A plain Dictionary makes no order promise. A sorted listing copies the keys into a list and sorts the copy first.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does TryGetValue return when the key is not in the dictionary?