基礎から学ぶC#入門 90日コース | 配列・コレクション・文字列 - Day 24:Dictionary

C# 90日で身につけるC#
スポンサーリンク
スポンサーリンク

Day 24 のゴールと全体像

Day 24 では、コレクションの中でもとても強力な Dictionary<TKey, TValue> を学びます。 Dictionary は「キーと値のペア」を管理するためのコレクションで、 設定値の管理、ID と名前の対応表、コードと説明文のマッピングなど、現場で頻繁に使われます。

学ぶ内容は次のとおりです。

  • キーと値
  • Add
  • ContainsKey
  • TryGetValue
  • Remove

これらをステップバイステップで理解しながら、 「キーで素早く値を取り出す」という発想を身につけていきます。

キーと値とは

「名前付きの値」を管理するコレクション

Dictionary<TKey, TValue> は、

「キー」と呼ばれる識別子と、「値」をペアで管理するコレクション

です。

イメージとしては、次のような「辞書」を思い浮かべると分かりやすいです。

  • キー:単語(例:"apple"
  • 値:意味(例:"りんご"

プログラムでは、例えば次のような対応を持たせることができます。

  • キー:商品コード(例:"A001"
  • 値:商品名(例:"りんごジュース"

Dictionary の基本的な宣言

using System;
using System.Collections.Generic; // Dictionary を使うために必要

class Program
{
    static void Main(string[] args)
    {
        // キーが string、値が int の Dictionary
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // キーが int、値が string の Dictionary
        Dictionary<int, string> errorMessages = new Dictionary<int, string>();

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • Dictionary<TKey, TValue>TKey がキーの型、TValue が値の型です。
  • キーは「重複なし」が前提です。同じキーを 2 回追加することはできません。

Add:キーと値のペアを追加する

「このキーにはこの値」と登録する

Add メソッドは、

新しいキーと値のペアを Dictionary に追加する

ためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // キーと値のペアを追加します
        ages.Add("Alice", 25);
        ages.Add("Bob", 30);
        ages.Add("Charlie", 28);

        // キーを使って値を取り出します
        Console.WriteLine($"Alice の年齢: {ages["Alice"]}");
        Console.WriteLine($"Bob の年齢: {ages["Bob"]}");

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • Add("Alice", 25) のように、キーと値をセットで登録します。
  • すでに存在するキーを Add しようとすると、例外が発生します。

ContainsKey:キーが存在するか確認する

「このキーは登録されている?」を安全にチェック

ContainsKey メソッドは、

指定したキーが Dictionary に存在するかどうか

を調べるためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 25 },
            { "Bob", 30 }
        };

        Console.Write("検索する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            if (ages.ContainsKey(name))
            {
                Console.WriteLine($"{name} の年齢は {ages[name]} 歳です。");
            }
            else
            {
                Console.WriteLine($"{name} は登録されていません。");
            }
        }

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • ContainsKey(key) は、キーが存在すれば true、存在しなければ false を返します。
  • キーが存在しないのに ages[key] とすると例外が出るので、 事前に ContainsKey でチェックするのが安全です。

TryGetValue:例外を出さずに値を取得する

「あれば値を返し、なければ失敗を知らせる」

TryGetValue は、

キーが存在する場合は値を取り出し、存在しない場合は失敗を返す

ためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 25 },
            { "Bob", 30 }
        };

        Console.Write("検索する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            // TryGetValue は、値を out パラメータで返します
            if (ages.TryGetValue(name, out int age))
            {
                Console.WriteLine($"{name} の年齢は {age} 歳です。");
            }
            else
            {
                Console.WriteLine($"{name} は登録されていません。");
            }
        }

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • TryGetValue(key, out value) は、
    • 成功したら true を返し、value に値が入る
    • 失敗したら false を返し、value にはデフォルト値が入る
  • 例外を出さずに安全に値を取得したいときに便利です。

Remove:キーを指定して削除する

「このキーのペアを消したい」

Remove メソッドは、

指定したキーに対応するキーと値のペアを削除する

ためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> ages = new Dictionary<string, int>
        {
            { "Alice", 25 },
            { "Bob", 30 },
            { "Charlie", 28 }
        };

        Console.WriteLine("=== 削除前 ===");
        PrintDictionary(ages);

        Console.Write("\n削除する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            bool removed = ages.Remove(name);

            if (removed)
            {
                Console.WriteLine($"\"{name}\" を削除しました。");
            }
            else
            {
                Console.WriteLine($"\"{name}\" は登録されていません。");
            }
        }

        Console.WriteLine("\n=== 削除後 ===");
        PrintDictionary(ages);

        Console.ReadLine();
    }

    static void PrintDictionary(Dictionary<string, int> dict)
    {
        Console.WriteLine("=== 登録されているデータ ===");
        foreach (var pair in dict)
        {
            Console.WriteLine($"キー: {pair.Key}, 値: {pair.Value}");
        }

        if (dict.Count == 0)
        {
            Console.WriteLine("(辞書は空です)");
        }
    }
}
C#

重要ポイント:

  • Remove(key) は、削除に成功したら true、キーがなければ false を返します。
  • 「キーで管理しているデータを消す」操作は、Dictionary の基本的な使い方のひとつです。

例題:国コードと国名の辞書を作る

Dictionary を「コード → 名前」の対応表として使う

ここまでのメソッドを組み合わせて、 簡単な「国コード → 国名」の辞書を作ってみます。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 国コードと国名の対応表
        Dictionary<string, string> countries = new Dictionary<string, string>
        {
            { "JP", "日本" },
            { "US", "アメリカ合衆国" },
            { "FR", "フランス" }
        };

        while (true)
        {
            Console.WriteLine();
            Console.WriteLine("=== 国コード辞書メニュー ===");
            Console.WriteLine("1: 国を追加");
            Console.WriteLine("2: 国コードで検索");
            Console.WriteLine("3: 国コードで削除");
            Console.WriteLine("4: 一覧表示");
            Console.WriteLine("0: 終了");
            Console.Write("番号を選んでください:");

            string? input = Console.ReadLine();

            if (input == "0")
            {
                Console.WriteLine("終了します。");
                break;
            }

            switch (input)
            {
                case "1":
                    AddCountry(countries);
                    break;

                case "2":
                    FindCountry(countries);
                    break;

                case "3":
                    RemoveCountry(countries);
                    break;

                case "4":
                    PrintCountries(countries);
                    break;

                default:
                    Console.WriteLine("不正な入力です。0〜4 の番号を選んでください。");
                    break;
            }
        }
    }

    // 国を追加する
    static void AddCountry(Dictionary<string, string> dict)
    {
        Console.Write("追加する国コードを入力してください(例: JP):");
        string? code = Console.ReadLine();

        Console.Write("国名を入力してください:");
        string? name = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(name))
        {
            Console.WriteLine("コードと国名の両方を入力してください。");
            return;
        }

        if (dict.ContainsKey(code))
        {
            Console.WriteLine($"コード \"{code}\" はすでに登録されています。");
            return;
        }

        dict.Add(code, name);
        Console.WriteLine($"コード \"{code}\" と国名 \"{name}\" を追加しました。");
    }

    // 国コードで検索する
    static void FindCountry(Dictionary<string, string> dict)
    {
        Console.Write("検索する国コードを入力してください:");
        string? code = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(code))
        {
            Console.WriteLine("コードを入力してください。");
            return;
        }

        if (dict.TryGetValue(code, out string? name))
        {
            Console.WriteLine($"コード \"{code}\" の国名は \"{name}\" です。");
        }
        else
        {
            Console.WriteLine($"コード \"{code}\" は登録されていません。");
        }
    }

    // 国コードで削除する
    static void RemoveCountry(Dictionary<string, string> dict)
    {
        Console.Write("削除する国コードを入力してください:");
        string? code = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(code))
        {
            Console.WriteLine("コードを入力してください。");
            return;
        }

        bool removed = dict.Remove(code);

        if (removed)
        {
            Console.WriteLine($"コード \"{code}\" を削除しました。");
        }
        else
        {
            Console.WriteLine($"コード \"{code}\" は登録されていません。");
        }
    }

    // 一覧表示
    static void PrintCountries(Dictionary<string, string> dict)
    {
        Console.WriteLine("=== 登録されている国一覧 ===");
        Console.WriteLine($"件数: {dict.Count}");

        foreach (var pair in dict)
        {
            Console.WriteLine($"コード: {pair.Key}, 国名: {pair.Value}");
        }

        if (dict.Count == 0)
        {
            Console.WriteLine("(辞書は空です)");
        }
    }
}
C#

この例で体験できること:

  • AddContainsKeyTryGetValueRemove を組み合わせた実践的な使い方
  • Dictionary を「コード → 名前」の対応表として使う感覚
  • キーを軸にしたデータ管理のイメージ

練習テンプレート:Dictionary の基本形

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 学生IDと名前の対応表
        Dictionary<int, string> students = new Dictionary<int, string>();

        // 追加
        students.Add(1, "Alice");
        students.Add(2, "Bob");
        students.Add(3, "Charlie");

        // ContainsKey で存在確認
        if (students.ContainsKey(2))
        {
            Console.WriteLine($"ID 2 の学生は {students[2]} です。");
        }

        // TryGetValue で安全に取得
        if (students.TryGetValue(3, out string? name))
        {
            Console.WriteLine($"ID 3 の学生は {name} です。");
        }

        // Remove で削除
        students.Remove(1);

        // 一覧表示
        Console.WriteLine("=== 学生一覧 ===");
        foreach (var pair in students)
        {
            Console.WriteLine($"ID: {pair.Key}, 名前: {pair.Value}");
        }

        Console.ReadLine();
    }
}
C#

Day 24 のまとめ

Day 24 では、キーと値のペアを管理するコレクション Dictionary<TKey, TValue> を学びました。

  • キーと値:キーで値を素早く取り出すためのペア
  • Add:キーと値のペアを追加
  • ContainsKey:キーが存在するかどうかを確認
  • TryGetValue:例外を出さずに値を安全に取得
  • Remove:キーを指定してペアを削除

というメソッドを通して、

「キーを軸にしたデータ管理」

という考え方を身につけました。

Dictionary は、設定値、マスターデータ、ID と名前の対応表など、 実際のアプリケーションで非常に多く使われる重要なコレクションです。

ぜひ、

  • 自分で「コード → 名前」「ID → データ」の辞書をいくつか作ってみる
  • List<T> と組み合わせて、より複雑なデータ構造を考えてみる

といった練習を通して、 Dictionary を自然に使いこなせるようになっていってください。


Day 24 ミニ課題のゴールと全体像

Day 24 のミニ課題では、Dictionary<TKey, TValue> を使って「電話帳アプリ」を作ることを目標にします。 電話帳はまさに「キーと値」の世界で、

  • キー:名前
  • 値:電話番号

という形でデータを管理するのにとても向いています。

ここでは、

  • 名前をキー、電話番号を値として Dictionary に登録する
  • Add で追加し、ContainsKeyTryGetValue で検索し、Remove で削除する
  • 簡単なメニュー形式のコンソールアプリとしてまとめる

という流れで、ステップバイステップで解説していきます。

電話帳を Dictionary<string, string> で表現する

「名前 → 電話番号」の対応表を作る

電話帳アプリでは、

  • 名前(例:"山田太郎"
  • 電話番号(例:"090-1234-5678"

をペアで管理します。 これを Dictionary<string, string> で表現します。

using System;
using System.Collections.Generic; // Dictionary を使うために必要

class Program
{
    static void Main(string[] args)
    {
        // 電話帳:キーが名前、値が電話番号
        Dictionary<string, string> phoneBook = new Dictionary<string, string>();

        Console.ReadLine();
    }
}
C#

ポイント:

  • Dictionary<string, string> は「文字列キー → 文字列値」の辞書です。
  • ここでは「名前 → 電話番号」という対応を持たせます。

Add:電話帳に登録する

名前と電話番号をセットで追加する

Add メソッドで、電話帳に新しいエントリを登録します。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> phoneBook = new Dictionary<string, string>();

        // 電話帳に登録します
        phoneBook.Add("山田太郎", "090-1234-5678");
        phoneBook.Add("佐藤花子", "080-9876-5432");

        // 登録内容を表示します
        PrintPhoneBook(phoneBook);

        Console.ReadLine();
    }

    // 電話帳の中身を表示するメソッド
    static void PrintPhoneBook(Dictionary<string, string> book)
    {
        Console.WriteLine("=== 電話帳 ===");
        foreach (var entry in book)
        {
            Console.WriteLine($"名前: {entry.Key}, 電話番号: {entry.Value}");
        }

        if (book.Count == 0)
        {
            Console.WriteLine("(電話帳は空です)");
        }
    }
}
C#

重要ポイント:

  • Add(キー, 値) で、名前と電話番号をセットで登録します。
  • 同じ名前(キー)を 2 回 Add しようとすると例外が発生するため、 実際のアプリでは事前に ContainsKey でチェックするのが安全です。

ContainsKey:登録済みかどうか確認する

「この名前はもう電話帳にある?」

ContainsKey は、

指定したキー(名前)が電話帳に登録されているかどうか

を確認するためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> phoneBook = new Dictionary<string, string>
        {
            { "山田太郎", "090-1234-5678" },
            { "佐藤花子", "080-9876-5432" }
        };

        Console.Write("検索する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            if (phoneBook.ContainsKey(name))
            {
                Console.WriteLine($"{name} さんは登録されています。");
                Console.WriteLine($"電話番号: {phoneBook[name]}");
            }
            else
            {
                Console.WriteLine($"{name} さんは電話帳に登録されていません。");
            }
        }

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • ContainsKey(name) は、
    • 登録されていれば true
    • 登録されていなければ false を返します。
  • キーが存在しないのに phoneBook[name] とすると例外が出るため、 事前に ContainsKey でチェックするのが安全です。

TryGetValue:安全に電話番号を取得する

「あれば番号を返し、なければ失敗を知らせる」

TryGetValue は、

キーが存在する場合は値(電話番号)を取り出し、存在しない場合は失敗を返す

ためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> phoneBook = new Dictionary<string, string>
        {
            { "山田太郎", "090-1234-5678" },
            { "佐藤花子", "080-9876-5432" }
        };

        Console.Write("検索する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            // TryGetValue は、値を out パラメータで返します
            if (phoneBook.TryGetValue(name, out string? phoneNumber))
            {
                Console.WriteLine($"{name} さんの電話番号は {phoneNumber} です。");
            }
            else
            {
                Console.WriteLine($"{name} さんは電話帳に登録されていません。");
            }
        }

        Console.ReadLine();
    }
}
C#

重要ポイント:

  • TryGetValue(key, out value) は、
    • 成功したら true を返し、value に電話番号が入る
    • 失敗したら false を返し、value には null(またはデフォルト値)が入る
  • 例外を出さずに安全に値を取得したいときに非常に便利です。

Remove:電話帳から削除する

「この人の登録を消したい」

Remove は、

指定したキー(名前)に対応するエントリを削除する

ためのメソッドです。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> phoneBook = new Dictionary<string, string>
        {
            { "山田太郎", "090-1234-5678" },
            { "佐藤花子", "080-9876-5432" },
            { "鈴木一郎", "070-1111-2222" }
        };

        Console.WriteLine("=== 削除前の電話帳 ===");
        PrintPhoneBook(phoneBook);

        Console.Write("\n削除する名前を入力してください:");
        string? name = Console.ReadLine();

        if (!string.IsNullOrWhiteSpace(name))
        {
            bool removed = phoneBook.Remove(name);

            if (removed)
            {
                Console.WriteLine($"\"{name}\" さんの登録を削除しました。");
            }
            else
            {
                Console.WriteLine($"\"{name}\" さんは電話帳に登録されていません。");
            }
        }

        Console.WriteLine("\n=== 削除後の電話帳 ===");
        PrintPhoneBook(phoneBook);

        Console.ReadLine();
    }

    static void PrintPhoneBook(Dictionary<string, string> book)
    {
        Console.WriteLine("=== 電話帳 ===");
        foreach (var entry in book)
        {
            Console.WriteLine($"名前: {entry.Key}, 電話番号: {entry.Value}");
        }

        if (book.Count == 0)
        {
            Console.WriteLine("(電話帳は空です)");
        }
    }
}
C#

重要ポイント:

  • Remove(name) は、削除に成功したら true、 該当する名前がなければ false を返します。
  • 電話帳のような「キーで管理するデータ」を扱うとき、削除はよく使う操作です。

ミニ課題完成版:対話型電話帳アプリ

メニュー形式で操作できるコンソールアプリ

ここまでの要素を組み合わせて、 ユーザーがメニューから操作できる簡単な電話帳アプリを作ってみます。

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 電話帳:名前 → 電話番号
        Dictionary<string, string> phoneBook = new Dictionary<string, string>();

        while (true)
        {
            Console.WriteLine();
            Console.WriteLine("=== 電話帳メニュー ===");
            Console.WriteLine("1: 登録");
            Console.WriteLine("2: 名前で検索");
            Console.WriteLine("3: 名前で削除");
            Console.WriteLine("4: 一覧表示");
            Console.WriteLine("0: 終了");
            Console.Write("番号を選んでください:");

            string? input = Console.ReadLine();

            if (input == "0")
            {
                Console.WriteLine("終了します。");
                break;
            }

            switch (input)
            {
                case "1":
                    AddEntry(phoneBook);
                    break;

                case "2":
                    FindEntry(phoneBook);
                    break;

                case "3":
                    RemoveEntry(phoneBook);
                    break;

                case "4":
                    PrintPhoneBook(phoneBook);
                    break;

                default:
                    Console.WriteLine("不正な入力です。0〜4 の番号を選んでください。");
                    break;
            }
        }
    }

    // 登録
    static void AddEntry(Dictionary<string, string> book)
    {
        Console.Write("登録する名前を入力してください:");
        string? name = Console.ReadLine();

        Console.Write("電話番号を入力してください:");
        string? phoneNumber = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(phoneNumber))
        {
            Console.WriteLine("名前と電話番号の両方を入力してください。");
            return;
        }

        if (book.ContainsKey(name))
        {
            Console.WriteLine($"\"{name}\" さんはすでに登録されています。");
            return;
        }

        book.Add(name, phoneNumber);
        Console.WriteLine($"\"{name}\" さん({phoneNumber})を電話帳に登録しました。");
    }

    // 名前で検索
    static void FindEntry(Dictionary<string, string> book)
    {
        Console.Write("検索する名前を入力してください:");
        string? name = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(name))
        {
            Console.WriteLine("名前を入力してください。");
            return;
        }

        if (book.TryGetValue(name, out string? phoneNumber))
        {
            Console.WriteLine($"\"{name}\" さんの電話番号は {phoneNumber} です。");
        }
        else
        {
            Console.WriteLine($"\"{name}\" さんは電話帳に登録されていません。");
        }
    }

    // 名前で削除
    static void RemoveEntry(Dictionary<string, string> book)
    {
        Console.Write("削除する名前を入力してください:");
        string? name = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(name))
        {
            Console.WriteLine("名前を入力してください。");
            return;
        }

        bool removed = book.Remove(name);

        if (removed)
        {
            Console.WriteLine($"\"{name}\" さんの登録を削除しました。");
        }
        else
        {
            Console.WriteLine($"\"{name}\" さんは電話帳に登録されていません。");
        }
    }

    // 一覧表示
    static void PrintPhoneBook(Dictionary<string, string> book)
    {
        Console.WriteLine("=== 電話帳一覧 ===");
        Console.WriteLine($"件数: {book.Count}");

        foreach (var entry in book)
        {
            Console.WriteLine($"名前: {entry.Key}, 電話番号: {entry.Value}");
        }

        if (book.Count == 0)
        {
            Console.WriteLine("(電話帳は空です)");
        }
    }
}
C#

この完成版で体験できること:

  • Dictionary<string, string> を使った「名前 → 電話番号」の管理
  • AddContainsKeyTryGetValueRemove の実践的な使い方
  • メニュー形式の簡易アプリの構成

Day 24 ミニ課題のまとめ

このミニ課題では、

  • 電話帳を Dictionary<string, string> で表現する
  • 名前をキー、電話番号を値として登録・検索・削除する
  • AddContainsKeyTryGetValueRemove を組み合わせた電話帳アプリを作る

という流れで、Dictionary を実際の用途に結びつけて学びました

Dictionary は、

「キーで素早く値を取り出す」

ための強力なコレクションです。

ぜひ、

  • 電話帳に「メールアドレス」や「住所」などの情報を追加してみる(後にクラス化へ発展できます)
  • キーを電話番号にして、値を名前にするなど、構造を入れ替えてみる

といったアレンジを加えながら、 キーと値の発想を自分のプログラムの中で自然に使いこなせるようになっていってください。

タイトルとURLをコピーしました