ディクショナリ(Dictionary)を使用したプログラミングにおいて、ディクショナリ(Dictionary)に含まれている全てのキーや値に対して処理を行いたい場合があると思います。
この記事では、C#のディクショナリ(Dictionary)クラスを使ってキーまたは値を列挙する方法について紹介します。
ディクショナリのキーの列挙
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// ディクショナリの初期化
Dictionary<string, int> fruits = new Dictionary<string, int>
{
{"apple", 1},
{"banana", 2},
{"cherry", 3}
};
// キーの列挙
foreach (var key in fruits.Keys)
{
Console.WriteLine(key);
}
}
}
実行結果

ディクショナリの値の列挙
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// ディクショナリの初期化
Dictionary<string, int> fruits = new Dictionary<string, int>
{
{"apple", 1},
{"banana", 2},
{"cherry", 3}
};
// 値の列挙
foreach (var value in fruits.Values)
{
Console.WriteLine(value);
}
}
}
実行結果

まとめ
この記事では、C#のディクショナリ(Dictionary)クラスを使ってキーまたは値を列挙する方法について紹介しました。