C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#のDictionaryクラスとは?基本構文と使い方を実例付きで解説

C#におけるDictionary(ディクショナリ)は、キー(Key)と値(Value)のペアを格納するコレクションクラスです。System.Collections.Generic名前空間に属するジェネリックコレクションであり、キーを使って高速に値へアクセスできるのが大きな特徴です。

辞書型は、実生活での「英和辞典」に似ています。単語(キー)を引けば、その意味(値)がすぐに分かる仕組みと同じで、プログラム内でもキーを指定するだけで対応する値を効率よく取得できます。

Dictionaryクラスの基本構文

Dictionaryクラスの宣言は以下のように行います。

public class Dictionary<TKey,TValue>

ここで、TKeyは辞書内のキーの型、TValueは値の型を表します。たとえば、文字列のキーに対して文字列の値を格納する場合はDictionary<string, string>のように指定します。

要素の追加と表示のサンプルコード

まずは、Dictionaryを作成して要素を追加し、すべてのキーと値のペアを表示する基本的な例を見てみましょう。

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main(){
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "John");
        dict.Add("Two", "Tom");
        dict.Add("Three", "Jacob");
        dict.Add("Four", "Kevin");
        dict.Add("Five", "Nathan");
        Console.WriteLine("Key/value pairs...");
        foreach(KeyValuePair<string, string> res in dict){
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
    }
}

実行結果

上記のコードを実行すると、次のような出力が得られます。

Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan

このように、Add()メソッドでキーと値のペアを追加し、foreachループとKeyValuePair<TKey,TValue>を使うことで、格納された全要素を順番に取り出して表示できます。

要素の削除とキー一覧の取得

続いて、特定のキーを持つ要素を削除したり、残っているキーの一覧を取得したりする例を紹介します。

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main(){
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "Kagido");
        dict.Add("Two", "Ngidi");
        dict.Add("Three", "Devillers");
        dict.Add("Four", "Smith");
        dict.Add("Five", "Warner");
        Console.WriteLine("Count of elements = "+dict.Count);
        Console.WriteLine("Removing some keys...");
        dict.Remove("Four");
        dict.Remove("Five");
        Console.WriteLine("Count of elements (updated) = "+dict.Count);
        Console.WriteLine("\nKey/value pairs...");
        foreach(KeyValuePair<string, string> res in dict){
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
        Console.Write("\nAll the keys..\n");
        Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
        foreach(string str in allKeys){
            Console.WriteLine("Key = {0}", str);
        }
    }
}

実行結果

このコードを実行すると、以下の出力になります。

Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three

ポイントまとめ

  • Add()メソッド:キーと値のペアを辞書に追加します。同じキーを追加しようとすると例外が発生するので注意が必要です。
  • Remove()メソッド:指定したキーに対応する要素を削除します。該当するキーが存在しない場合はfalseを返します。
  • Countプロパティ:現在格納されている要素数を取得できます。
  • Keysプロパティ:辞書内のすべてのキーを含むKeyCollectionを返します。

Dictionaryクラスは、検索速度が非常に速く(内部的にはハッシュテーブルを使用)、大量のデータから特定の値を探す場面で特に威力を発揮します。C#でのデータ管理において必須ともいえるクラスなので、ぜひ使いこなせるようになりましょう。

  1. C#のConvertクラスを使ったデータ型変換の基本と実例

    C#のConvertクラスには、基本データ型を別の基本データ型へ変換するためのメソッドが多数用意されています。この記事では、代表的な変換メソッドであるConvert.ToBoolean()、Convert.ToDouble()、Convert.ToDecimal()の使い方を、構文・サンプルコード・実行結果とあわせてわかりやすく解説します。 Convert.ToBoolean()メソッドとは Convert.ToBoolean()メソッドは、指定した値を等価なBoolean(真偽値)に変換します。文字列「true」や「false」をbool型に変換したい場合などに利用されます。 構文 pu

  2. C#のConsoleクラスとは?主要プロパティの使い方を実例付きで解説

    C#のConsoleクラスは、コンソールアプリケーションにおける標準入力・標準出力・標準エラー出力の各ストリームを表すクラスです。テキストの表示や入力の読み取りだけでなく、文字色や背景色の変更、カーソル位置やサイズの制御など、コンソール操作に関するさまざまな機能が提供されています。ここでは、Consoleクラスの代表的なプロパティの使い方を、サンプルコードと実行結果とあわせて解説します。Console.CursorLeftプロパティコンソール上のカーソル位置(左端から数えた列位置)を変更するには、Console.CursorLeftプロパティを使用します。サンプルコードusing System