C# 辞書をループ処理する

C#で、辞書をループ処理するサンプルコードを記述してます。「foreach」と「for」文どちらを使用してもループ処理は可能です。実行環境はVisual Studioをです。
環境
- OS windows11 pro 64bit
- Microsoft Visual Studio Community 2022 Version 17.2.6
辞書をループ処理
辞書をループ処理するには、「foreach」などを使用します。
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>()
{
{1,"v1"},
{2,"v2"},
{3,"v3"}
};
foreach (var i in dict) {
System.Console.WriteLine( i.Key + " " + i.Value );
}
}
}
}
実行結果

for文
「for文」でも可能です。
using System;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>()
{
{1,"v1"},
{2,"v2"},
{3,"v3"}
};
for (int i = 0; i < dict.Count; i++)
{
System.Console.WriteLine( i + " " + dict[i+1] );
}
}
}
}
-
前の記事
javascript 1つ次のページに進む 2022.10.25
-
次の記事
sakuraエディタ ステータスバーの表示・非表示を切り替えるショートカットキー 2022.10.25
コメントを書く