2
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#】色々なforeachの使用方法【初心者向け】

Last updated at Posted at 2024-10-02

概要

単なるリストや配列以外をforeachで回すサンプルコードを記載しました。

基本的なforeach文は以下のようになると思います。

    List<string> collection = new List<string>(){"hoge","fuga","piyo"};
    foreach (var item in collection)
    {
        // 処理
    }

上記以外の、タプルやディクショナリ等を使用したforeachのサンプルコードをまとめました。

目次

タプルを使用したforeach文

    Tuple<int, string, bool>[] tuples = { Tuple.Create(0, "hoge", true), Tuple.Create(1, "fuga", false) };
    foreach (var (first, second, third) in tuples)
    {
      // 処理
        Console.WriteLine($"1つ目: {first}, 2つ目: {second},3つ目: {third}");
    }

Dictonaryを使用したforeach文

    var dic = new Dictionary<string, int>
    {
        {"田中さん", 37},
        {"山田さん", 42},
        {"佐藤さん", 24}
    };

    foreach (var pair in dic)
    {
        // 処理
        Console.WriteLine($"{pair.Key}{pair.Value} 歳です。");
    }

また、以下のような拡張関数を記載しておくことで、

    static class KeyvalueExtensions {
        public static void Deconstruct<K,V>(this KeyValuePair<K,V> self, out K k, out V v)
            => (k, v) = (self.Key, self.Value);
    }

以下のように回すことも可能です。

    var dic = new Dictionary<string, int>
    {
        {"田中さん", 37},
        {"山田さん", 42},
        {"佐藤さん", 24}
    };
    
    foreach (var (k, v) in dic)
    {
        // 処理
        Console.WriteLine($"{k}{v} 歳です。");
    }

コレクションを合体させたものを回すforeach文

    var names = new List<string> { "田中さん", "山田さん", "佐藤さん" };
    var ages = new List<int> { 37, 42, 24 };
    
    var results = names.Zip(ages, (n, a) => new { Name = n, Age = a });
    foreach (var pair in results)
    {
        // 処理
        Console.WriteLine($"{pair.Name}{pair.Age} 歳です。");
    }

LINQのZipメソッドは、2のコレクションを1つに合体させることができるメソッドです。

以下のように書くと、よりわかりやすくなります。

    var names = new List<string> { "田中さん", "山田さん", "佐藤さん" };
    var ages = new List<int> { 37, 42, 24 };
    
    var results = names.Zip(ages);
    foreach (var (name, age) in results)
    {
        // 処理
        Console.WriteLine($"{name}{age} 歳です。");
    }

参照渡しのforeach文

{
    var names = new string[] { "田中さん", "山田さん", "佐藤さん" };
    foreach(ref var name in names.AsSpan())
        name += "2";

    // 処理
    Console.WriteLine($"{string.Join(", ", names)}");
}

終わりに

使用箇所は少ないかもしれませんが、使用できる場面で使用せず冗長?なコードにならないように気を付けたいです。

2
1
6

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
2
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?