C#でDictionaryを反復処理する列挙子を取得する方法(GetEnumeratorの使い方)
C#のDictionary<TKey, TValue>クラスでは、GetEnumerator()メソッドを呼び出すことで、ディクショナリ内のキーと値のペアを順番に走査する列挙子(Enumerator)を取得できます。戻り値はIDictionaryEnumerator型として扱うことができ、MoveNext()メソッドで次の要素へ移動しながら、KeyプロパティとValueプロパティでそれぞれキーと値を読み取ります。
例1:int型のキーを持つDictionaryの場合
まずは、キーがint型・値がstring型のディクショナリを作成し、列挙子を使って全要素を表示する基本例を見てみましょう。
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(100, "Laptop");
dict.Add(150, "Desktop");
dict.Add(200, "Earphone");
dict.Add(300, "Tablet");
dict.Add(500, "Speakers");
dict.Add(750, "HardDisk");
dict.Add(1000, "SSD");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("列挙子でキーと値のペアを反復処理しています...");
while (demoEnum.MoveNext())
Console.WriteLine("キー = " + demoEnum.Key + ", 値 = " + demoEnum.Value);
}
}
出力結果
上記のプログラムを実行すると、次のように登録されたすべてのキーと値のペアが出力されます。
列挙子でキーと値のペアを反復処理しています... キー = 100, 値 = Laptop キー = 150, 値 = Desktop キー = 200, 値 = Earphone キー = 300, 値 = Tablet キー = 500, 値 = Speakers キー = 750, 値 = HardDisk キー = 1000, 値 = SSD
例2:string型のキーを持つDictionaryの場合
続いて、キーも値もstring型であるディクショナリに対して、同じ手順で列挙子を取得し、反復処理を行う例を紹介します。
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Laptop");
dict.Add("Two", "Desktop");
dict.Add("Three", "Earphone");
dict.Add("Four", "Tablet");
dict.Add("Five", "Speakers");
dict.Add("Six", "HardDisk");
dict.Add("Seven", "SSD");
dict.Add("Eight", "Keyboard");
dict.Add("Nine", "Mouse");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
Console.WriteLine("列挙子でキーと値のペアを反復処理しています...");
while (demoEnum.MoveNext())
Console.WriteLine("キー = " + demoEnum.Key + ", 値 = " + demoEnum.Value);
}
}
出力結果
実行すると、9つの要素がすべて順番に出力されます。
列挙子でキーと値のペアを反復処理しています... キー = One, 値 = Laptop キー = Two, 値 = Desktop キー = Three, 値 = Earphone キー = Four, 値 = Tablet キー = Five, 値 = Speakers キー = Six, 値 = HardDisk キー = Seven, 値 = SSD キー = Eight, 値 = Keyboard キー = Nine, 値 = Mouse
コードのポイント
- GetEnumerator()メソッド: ディクショナリを反復処理するための列挙子オブジェクトを返します。
Dictionary<TKey, TValue>.Enumerator構造体はIDictionaryEnumeratorインターフェースを実装しているため、そのまま変数に代入できます。 - MoveNext()メソッド: 次の要素が存在する場合は
trueを返して列挙子を前進させ、末尾に達するとfalseを返します。whileループの継続条件として機能します。 - Key / Valueプロパティ: 列挙子の現在位置にあるキーと値をそれぞれ取得できます。
- foreachとの比較: 単純な反復処理であれば
foreach (var kvp in dict)の方が簡潔に書けますが、IDictionaryEnumeratorを使うとEntry、Key、Valueといった辞書専用のプロパティに明示的にアクセスできるのが特徴です。
なお、列挙中にディクショナリへ要素の追加や削除を行うとInvalidOperationExceptionが発生する場合があるため、反復処理中はコレクションを変更しないよう注意してください。
-
C#で大文字と小文字を区別しないDictionary(辞書)を作成する方法
C#で大文字と小文字を区別しないDictionaryを使うには C#のDictionaryは、デフォルトではキーの大文字と小文字を区別します。そのため、cricketとCRICKETは異なるキーとして扱われます。 大文字と小文字を区別せずにキーを比較したい場合は、Dictionaryを宣言するときに比較子としてStringComparer.OrdinalIgnoreCaseを指定します。 大文字・小文字を無視するDictionaryの宣言方法 コンストラクタの引数にStringComparer.OrdinalIgnoreCaseを渡すだけで、大文字と小文字を区別しないDictionaryを作
-
【C#】Dictionaryからキーのリストを取得する方法
C#では、Dictionary<TKey, TValue> に格納されたすべてのキーを、List<TKey> として簡単に取り出すことができます。この記事では、Keys プロパティを使ってキーの一覧をリスト化し、画面に表示するまでの手順をサンプルコード付きで解説します。 Dictionaryに要素を追加する まずは、辞書(Dictionary)に要素を設定しましょう。 Dictionary<int, string> d = new Dictionary<int, string>(); // 辞書の要素 d.Add(1, "One&q