英語で読む

次の方法で共有


Array.ForEach<T>(T[], Action<T>) メソッド

定義

指定された配列内の各要素に対して、指定された処理を実行します。

C#
public static void ForEach<T>(T[] array, Action<T> action);

型パラメーター

T

配列要素の型。

パラメーター

array
T[]

要素に処理を適用する、インデックス番号が 0 から始まる 1 次元の Array

action
Action<T>

array の各要素に対して実行する Action<T>

例外

arraynullです。

または

actionnullです。

次の例は、 を使用 ForEach して、整数配列内の各要素の 2 乗を表示する方法を示しています。

C#
using System;

public class SamplesArray
{
    public static void Main()
    {
        // create a three element array of integers
        int[] intArray = new int[] {2, 3, 4};

        // set a delegate for the ShowSquares method
        Action<int> action = new Action<int>(ShowSquares);

        Array.ForEach(intArray, action);
    }

    private static void ShowSquares(int val)
    {
        Console.WriteLine("{0:d} squared = {1:d}", val, val*val);
    }
}

/*
This code produces the following output:

2 squared = 4
3 squared = 9
4 squared = 16
*/

注釈

Action<T>は、渡されたオブジェクトに対してアクションを実行するメソッドへのデリゲートです。 の array 要素は、 に個別に Action<T>渡されます。

このメソッドは O(n) 操作です。ここで nLength は の arrayです。

F# では、 代わりに Array.iter 関数を使用できます。

適用対象

製品 バージョン
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

こちらもご覧ください