3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】for と foreach どっちを使うべき?

Last updated at Posted at 2025-10-02

for の特徴

for は昔ながらのループ構文。インデックスを使って要素にアクセスします。

こんなときに便利

  • インデックスが必要なとき
for (int i = 0; i < arr.Length; i++)
{
    Console.WriteLine($"{i}番目: {arr[i]}");
}
  • 要素を飛ばして処理したいとき
for (int i = 0; i < arr.Length; i += 2)
{
    Console.WriteLine(arr[i]); // 偶数番目だけ
}
  • 逆順に処理したいとき
for (int i = list.Count - 1; i >= 0; i--)
{
    Console.WriteLine(list[i]);
}

foreach の特徴

foreach は「コレクションの要素を順番に処理する」ための構文。
インデックス不要で、コードがスッキリ書けます。

こんなときに便利

  • 単純に全要素を処理したいとき
foreach (var item in list)
{
    Console.WriteLine(item);
}
  • List, Dictionary などコレクションを扱うとき
foreach (var kv in dict)
{
    Console.WriteLine($"{kv.Key} = {kv.Value}");
}
  • 可読性を優先したいとき
    「全部の要素を処理してるんだな」と一目で分かる

使い分けの目安

  • 可読性重視 → foreach
  • インデックスや順序制御が必要 → for

基本的には foreachデフォルトで使う のがおすすめです。
インデックスが欲しい特殊なケースだけ for を選べばOK。

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?